301

I am trying to set a background image for the home page. I am getting the image place from start of the screen and filling the width but not the height. Am I missing something in my code? Are there image standards for flutter? Do images scale based on each phone's screen resolution?

class BaseLayout extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return  Scaffold(
      body:  Container(
        child:  Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
             Image.asset("assets/images/bulb.jpg") 
          ]
        )
      )
    );
  }
}
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
Arun Kumar
  • 3,251
  • 4
  • 14
  • 10

19 Answers19

709

I'm not sure I understand your question, but if you want the image to fill the entire screen you can use a DecorationImage with a fit of BoxFit.cover.

class BaseLayout extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/bulb.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        child: null /* add child content here */,
      ),
    );
  }
}

For your second question, here is a link to the documentation on how to embed resolution-dependent asset images into your app.

Aaditya
  • 17
  • 6
Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
  • 20
    This works as long you don't have any child. If you add a child then the size of the Container is shrunk to the size of its child. Do you know how to make the container fill all the screen no matter the size of its child? – HyLian Mar 09 '18 at 14:35
  • @ColinJackson what should be the size of the image? width*height? – ArgaPK Sep 25 '18 at 13:28
  • 19
    @HyLian set container's constraints property, `constraints: BoxConstraints.expand()` – Rustem Kakimov Jan 18 '20 at 02:14
  • 2
    @HyLian add ```width: double.infinity``` to the Container with the image. – jkoech Apr 07 '20 at 19:32
  • 1
    how to repeat pattern type image in container background in flutter? – Kamlesh Oct 11 '20 at 13:05
  • I works, but the animations of buttons disappear under the image ;(;( – trueToastedCode Dec 22 '20 at 21:15
  • @HyLian wrap the Container with SizedBox.expand – dilshan Feb 26 '21 at 07:46
  • @Collin and Rustem, both solutions are not working when keyboard is opened then background image is moved to upside and when keyboard is closed then background image is displayed in normal position. Not correct solution. Any other suggestion? Please share. Thanks. – Kamlesh Feb 28 '21 at 17:23
  • I get this what should I do? The argument type 'Object' can't be assigned to the parameter type 'ImageProvider. Found the solution in here https://stackoverflow.com/a/66598280/9960377 – Rafsan Uddin Beg Rizan Aug 08 '21 at 05:44
  • @Kamlesh, please look https://stackoverflow.com/a/70428060/2646022 for scrollable screen with static background image – utarid Dec 20 '21 at 21:13
  • just add height: double.infinity, width: double.infinity for full screen container with full screen background image – Rachit Vohera Dec 28 '21 at 11:51
  • This works for me with many child after removing assets from image path: – Deepak Ghadi Feb 19 '22 at 13:50
  • @Collin Jackson: This concept not working for me. SO : 73920939. I am waiting for your answer – EMahan K Oct 05 '22 at 11:27
81

If you use a Container as the body of the Scaffold, its size will be accordingly the size of its child, and usually that is not what you want when you try to add a background image to your app.

Looking at this other question, @collin-jackson was also suggesting to use Stack instead of Container as the body of the Scaffold and it definitely does what you want to achieve.

This is how my code looks like

@override
Widget build(BuildContext context) {
  return new Scaffold(
    body: new Stack(
      children: <Widget>[
        new Container(
          decoration: new BoxDecoration(
            image: new DecorationImage(image: new AssetImage("images/background.jpg"), fit: BoxFit.cover,),
          ),
        ),
        new Center(
          child: new Text("Hello background"),
        )
      ],
    )
  );
}
HyLian
  • 4,999
  • 5
  • 33
  • 40
43

Screenshot:

enter image description here


Code:

@override
Widget build(BuildContext context) {
  return DecoratedBox(
    decoration: BoxDecoration(
      image: DecorationImage(image: AssetImage("your_asset"), fit: BoxFit.cover),
    ),
    child: Center(child: FlutterLogo(size: 300)),
  );
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • Please put a text box and open the keyboard then image will be moved up, which is not good solution. Any other suggestion, please share. – Kamlesh Feb 28 '21 at 17:26
27

You can use Stack to make the image stretch to the full screen.

Stack(
        children: <Widget>
        [
          Positioned.fill(  //
            child: Image(
              image: AssetImage('assets/placeholder.png'),
              fit : BoxFit.fill,
           ),
          ), 
          ...... // other children widgets of Stack
          ..........
          .............
         ]
 );

Note: Optionally if are using a Scaffold, you can put the Stack inside the Scaffold with or without AppBar according to your needs.

Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71
  • Exactly what I needed, in my case my image is inside a `ShaderMask`, therefore it wouldn't work putting in a `image:` name. – Soon Santos Jan 26 '20 at 02:14
14

I was able to apply a background below the Scaffold (and even it's AppBar) by putting the Scaffold under a Stack and setting a Container in the first "layer" with the background image set and fit: BoxFit.cover property.

Both the Scaffold and AppBar has to have the backgroundColor set as Color.transparent and the elevation of AppBar has to be 0 (zero).

Voilà! Now you have a nice background below the whole Scaffold and AppBar! :)

import 'package:flutter/material.dart';
import 'package:mynamespace/ui/shared/colors.dart';
import 'package:mynamespace/ui/shared/textstyle.dart';
import 'package:mynamespace/ui/shared/ui_helpers.dart';
import 'package:mynamespace/ui/widgets/custom_text_form_field_widget.dart';

class SignUpView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack( // <-- STACK AS THE SCAFFOLD PARENT
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("assets/images/bg.png"), // <-- BACKGROUND IMAGE
              fit: BoxFit.cover,
            ),
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent, // <-- SCAFFOLD WITH TRANSPARENT BG
          appBar: AppBar(
            title: Text('NEW USER'),
            backgroundColor: Colors.transparent, // <-- APPBAR WITH TRANSPARENT BG
            elevation: 0, // <-- ELEVATION ZEROED
          ),
          body: Padding(
            padding: EdgeInsets.all(spaceXS),
            child: Column(
              children: [
                CustomTextFormFieldWidget(labelText: 'Email', hintText: 'Type your Email'),
                UIHelper.verticalSpaceSM,
                SizedBox(
                  width: double.maxFinite,
                  child: RaisedButton(
                    color: regularCyan,
                    child: Text('Finish Registration', style: TextStyle(color: white)),
                    onPressed: () => {},
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
Tuco
  • 1,620
  • 1
  • 14
  • 15
13

We can use Container and mark its height as infinity

body: Container(
      height: double.infinity,
      width: double.infinity,
      child: FittedBox(
        fit: BoxFit.cover,
        child: Image.network(
          'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
        ),
      ),
    ));

Output:

enter image description here

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
10

It can be done either of the following ways, based on the requirement

  1. Background image spanning accross the app Bar
  2. Background image not spanning accross the app Bar.

Background image spanning accross the app Bar

enter image description here

  Scaffold(
    extendBodyBehindAppBar: true,
    appBar: AppBar(
      elevation: 0,
      title: const Text(
        "Home Page",
        style: TextStyle(color: Colors.white),
      ),
      backgroundColor: Colors.transparent,
    ),
    body: Container(
      height: double.infinity,
      width: double.infinity,
      decoration: const BoxDecoration(
          image: DecorationImage(
              fit: BoxFit.fill,
              image: NetworkImage(
                  'https://wallpaperaccess.com/full/2440003.jpg'))
          child: < Your Widgets go here >

      ),
    ));

Background image not spanning accross the app Bar

enter image description here

   Scaffold(
    appBar: AppBar(
      elevation: 0,
      title: const Text(
        "Home Page",
        style: TextStyle(color: Colors.black),
      ),
      backgroundColor: Colors.transparent,
    ),
    body: Container(
      height: double.infinity,
      width: double.infinity,
      decoration: const BoxDecoration(
          image: DecorationImage(
              fit: BoxFit.fill,
              image: NetworkImage(
                  'https://wallpaperaccess.com/full/2440003.jpg'))
          child: < Your Widgets go here >

      ),
    ));

Extra :

To add background image only to the appBar refer this answer

krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
6
body: Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('images/background.png'),fit:BoxFit.cover
      )
    ),
);
Boken
  • 4,825
  • 10
  • 32
  • 42
  • The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer could benefit from an explanation. Code only answers are not considered "good" answers. – Trenton McKinney Aug 08 '20 at 06:14
5
decoration: BoxDecoration(
      image: DecorationImage(
        image: ExactAssetImage("images/background.png"),
        fit: BoxFit.cover
      ),
    ),

this also works inside a container.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
vinayak paste
  • 61
  • 1
  • 1
5

Other answers are great. This is another way it can be done.

  1. Here I use SizedBox.expand() to fill available space and for passing tight constraints for its children (Container).
  2. BoxFit.cover enum to Zoom the image and cover whole screen
 Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand( // -> 01
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
              fit: BoxFit.cover,    // -> 02
            ),
          ),
        ),
      ),
    );
  }

screenshot

dilshan
  • 2,045
  • 20
  • 18
5

Here is how you can achieve this. First example is with assets image and the second one is with network image.

Local image:

Container(
  height: 200,
  width: double.infinity,
  decoration: const BoxDecoration(
    image: DecorationImage(
        image: AssetImage("assets/images/cat2.jpg"), 
        fit: BoxFit.cover),
  ),
  child: 
)

Network image:

Container(
  height: 200,
  width: double.infinity,
  decoration: const BoxDecoration(
    image: DecorationImage(
        image: NetworkImage("https://picsum.photos/id/237/200/300"), 
        fit: BoxFit.cover),
  ),
  child:
)
ejuhjav
  • 2,660
  • 2
  • 21
  • 32
Anand PS
  • 101
  • 2
  • 9
4

To set a background image without shrinking after adding the child, use this code.

  body: Container(
    constraints: BoxConstraints.expand(),
      decoration: BoxDecoration(
        image: DecorationImage(
            image: AssetImage("assets/aaa.jpg"),
        fit: BoxFit.cover,
        )
      ),

    //You can use any widget
    child: Column(
      children: <Widget>[],
    ),
    ),
Dulya Perera
  • 147
  • 2
  • 11
  • Please put a text box and open the keyboard then image will be moved up, which is not good solution. Any other suggestion, please share. – Kamlesh Feb 28 '21 at 17:29
4

You can use the following code to set a background image to your app:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/background.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        // use any child here
        child: null
      ),
    );
  }

If your Container's child is a Column widget, you can use the crossAxisAlignment: CrossAxisAlignment.stretch to make your background image fill the screen.

lcarvalho
  • 71
  • 1
  • 4
4

I know there is a lot of answers to this question already, but this solution comes with a color gradient around the background image, I think you would like it

import 'package:flutter/material.dart';

class BackgroundImageExample extends StatelessWidget {
  const BackgroundImageExample({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        backgroudImage(),
        Scaffold(
          backgroundColor: Colors.transparent,
          body: SafeArea(
            child: Column(
              children: [
                // your body content here
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget backgroudImage() {
    return ShaderMask(
      shaderCallback: (bounds) => LinearGradient(
        colors: [Colors.black, Colors.black12],
        begin: Alignment.bottomCenter,
        end: Alignment.center,
      ).createShader(bounds),
      blendMode: BlendMode.darken,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('your image here'), /// change this to your  image directory 
            fit: BoxFit.cover,
            colorFilter: ColorFilter.mode(Colors.black45, BlendMode.darken),
          ),
        ),
      ),
    );
  }
}
techwithsam
  • 285
  • 3
  • 7
4
Stack(
   children: [
         SizedBox.expand(
              child: FittedBox(
                    fit: BoxFit.cover,
                    child: Image.asset(
                      Images.splashBackground,
                    ),
                 )
          ),
          your widgets
     ])

This Helped me

3

You can use FractionallySizedBox

Sometimes decoratedBox doesn't cover the full-screen size. We can fix it by wrapping it with FractionallySizedBox Widget. In this widget we give widthfactor and heightfactor.

The widthfactor shows the [FractionallySizedBox]widget should take _____ percentage of the app's width.

The heightfactor shows the [FractionallySizedBox]widget should take _____ percentage of the app's height.

Example : heightfactor = 0.3 means 30% of app's height. widthfactor = 0.4 means 40% of app's width.

        Hence, for full screen set heightfactor = 1.0 and widthfactor = 1.0

Tip: FractionallySizedBox goes well with the stack widget. So that you can easily add buttons, avatars, texts over your background image in the stack widget whereas in rows and columns you cannot do that.

For more info check out this project's repository github repository link for this project

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Stack(
            children: <Widget>[
              Container(
                child: FractionallySizedBox(
                  heightFactor: 1.0,
                  widthFactor: 1.0,
                  //for full screen set heightFactor: 1.0,widthFactor: 1.0,
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage("images/1.jpg"),
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}



OutPut: enter image description here

Ruby TR
  • 41
  • 4
3
import 'package:flutter/material.dart';

void main() => runApp(DestiniApp());

class DestiniApp extends StatefulWidget {
  @override
  _DestiniAppState createState() => _DestiniAppState();
}

class _DestiniAppState extends State<DestiniApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: SafeArea(
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: Color.fromRGBO(245, 0, 87, 1),
            title: Text(
              "Landing Page Bankground Image",
            ),
          ),
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: ExactAssetImage("images/appBack.jpg"),
                  fit: BoxFit.cover
              ),
            ),
          ),
        ),
      ),
    );
  }
}

Output: enter image description here

Ridoy Paul
  • 49
  • 4
3
    @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
            child: Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
            image: AssetImage('assets/bgmain.jpg'),
            //fit: BoxFit.cover 
            fit: BoxFit.fill),
      ),
      child: Column(
        children: 
        [
          //
        ],
      ),
    )));
  }
Suresh B B
  • 1,387
  • 11
  • 13
3
            Image.asset(
              "assets/images/background.png",
              fit: BoxFit.cover,
              height: double.infinity,
              width: double.infinity,
              alignment: Alignment.center,
            ),

if still there is a problèm, it' seem like your image is not perfection in the heigth and width