Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To add a background image in Flutter, follow these steps:

  1. Import the dart:ui library to use the Image class.

  2. In the build method of your widget tree, add a Stack widget to hold the background image and other elements.

  3. Add a Container widget as the first child of the Stack widget. This will contain the background image.

  4. In the decoration property of the Container widget, use the BoxDecoration class to add a background image. You can do this by specifying the image property with an instance of the DecorationImage class.

Example code:

import 'dart:ui' as ui;

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/background.jpg'),
              fit: BoxFit.cover,
            ),
          ),
          child: null,
        ),
        // Add other widgets on top of the background image here
      ],
    );
  }
}

In this example, we import the dart:ui library as ui, which provides the Image class used by Flutter to load images. We then create a new Stack widget, with a Container widget as the first child. The DecorationImage class is used in the BoxDecoration of the Container to specify the background.jpg asset as the image to use for the background. The fit property of the DecorationImage is set to BoxFit.cover to ensure the image covers the entire container. Finally, any other widgets can be added to the Stack on top of the background image.