add bg image flutter

How to Add Background Image in Flutter

If you are developing a Flutter application and want to add a background image, it is a fairly simple process. There are a few ways to achieve this, so let me explain them in detail.

Method 1: Using the BoxDecoration Widget

The easiest way to add a background image in Flutter is by using the BoxDecoration widget. Here's how:

  1. Import the dart:ui library at the top of your file:
import 'dart:ui' as ui;
  1. Load the image using the AssetImage widget:
AssetImage('assets/images/background.jpg')
  1. Create a BoxDecoration widget with the background image:
BoxDecoration(
    image: DecorationImage(
      image: AssetImage('assets/images/background.jpg'),
      fit: BoxFit.cover,
    ),
  )
  1. Wrap your container with the BoxDecoration widget:
Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('assets/images/background.jpg'),
        fit: BoxFit.cover,
      ),
    ),
    child: ...
  )

Method 2: Using the Stack Widget

If you want more control over your layout, you can use the Stack widget to add a background image. Here's how:

  1. Load the image using the AssetImage widget:
AssetImage('assets/images/background.jpg')
  1. Create a Positioned widget with the background image:
Positioned(
    top: 0,
    left: 0,
    child: Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.jpg'),
          fit: BoxFit.cover,
        ),
      ),
    ),
  )
  1. Wrap your layout with the Stack widget:
Stack(
    children: [
      Positioned(
        top: 0,
        left: 0,
        child: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/background.jpg'),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
      ...
    ],
  )

Conclusion

Adding a background image in Flutter is a simple process, and there are multiple ways to do it. You can use the BoxDecoration widget for a simple approach or the Stack widget for more control over your layout. I hope this helps you in your Flutter development journey.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe