How to Set Asset or Network Image as Background on Container Widget

In this example, we are going to show you the way to set images from local assets or the internet as background on widgets like Container() or Card(). See the example below to see on details.

Container(
  height:200,
  decoration: BoxDecoration(
    image: DecorationImage(
      image: AssetImage("assets/nature/nature.jpg"),
      fit: BoxFit.cover,
    ),
  ),
)

You can simply change the value of "fit" attribute on DecorationImage() to change the way Image sets as a background.

Container(
  height:200,
  decoration: BoxDecoration(
    image: DecorationImage(
      image: NetworkImage("https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"),
      fit: BoxFit.cover,
    ),
  ),
)

Card( 
  child: Container(
    height:200,
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage("assets/nature/nature.jpg"),
        fit: BoxFit.cover,
      ),
    ),
  ),
)

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Set Image as Background"),
          backgroundColor: Colors.deepOrangeAccent,
        ),
        body: Container(
            padding: EdgeInsets.all(20),
            child: Column(
              children: [

                Container(
                  height:200,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("assets/nature/nature.jpg"),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),

                Container(
                  height:200,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: NetworkImage("https://cdn.pixabay.com/photo/2014/02/27/16/10/tree-276014_960_720.jpg"),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),

                Card( 
                  child: Container(
                    height:200,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage("assets/nature/nature.jpg"),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                )

              ],
            )
        )
    );
  }
}

In this way, you can set Asset or  Network image as Background on the widget in Flutter App.

No any Comments on this Article


Please Wait...