How to set the background in Flutter

Key takeaways:

  • Flutter supports multiple methods for setting backgrounds, including scaffoldBackgroundColor for global background settings, BoxDecoration for container-specific customization, and the Container widget's color property for simple color assignments.

  • Use DecorationImage within BoxDecoration to add background images. Adjust properties like fit using BoxFit.cover to control image scaling and placement.

  • Implement smooth transitions between colors using gradients like LinearGradient, RadialGradient, or SweepGradient with the BoxDecoration class for eye-catching designs.

  • While scaffoldBackgroundColor aligns with Material design principles, BoxDecoration offers flexibility for non-Material design applications with border and color customization.

  • Flutter enables layering child widgets on top of background colors or images, making it easy to create complex and dynamic layouts.

Flutter is an open-source framework and user-interface software development kit created by Google. Flutter is used to build natively compiled, multi-platform applications for Android, iOS, Linux, macOS, Windows, and the web from a single codebase. Flutter uses the Dart programming language, so any Flutter application will use Dart to create the various components of the application. A background in Flutter is the canvas against which the application performs its actions.

Types of background

There are three ways to set backgrounds in Flutter.

Change background color: There are three methods of setting the background color in Flutter.

  • Method 1: Set the background color for All Scaffolds by setting scaffoldBackgroundColor in ThemeData.

  • Method 2: Use a decoration such as a BoxDecoration in the Container object.

  • Method 3: Add the child widgets to the Container object.

Add background image: There is one method of setting the background image in Flutter. Use the DecorationImage and BoxDecoration classes.

Add gradient: Another option is setting a gradient background, which provides a smooth transition between multiple colors. Flutter offers different types of gradients, such as LinearGradient, RadialGradient, and SweepGradient, that can be applied using the BoxDecoration class in the Container widget.

Background color

Let's discuss each method one by one:

1. Using scaffoldBackgroundColor

The first way to set the background color is to use scaffoldBackgroundColor in ThemeData as follows:

MaterialApp(
title: 'Flutter background demo',
theme: ThemeData( scaffoldBackgroundColor: Colors.lightGreenAccent,),
home: MyHomePage(title: 'Flutter background demo page'),
);
Explanation
  • Line 3: Add the scaffoldBackgroundColor property in ThemeData and assign the color.

  • Line 4: Add a theme widget to the MaterialApp constructor. This will result in an identical background color for all scaffolds within the application.

Run the following code to understand how to use scaffoldBackgroundColor property.

import 'package:flutter/material.dart';

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

class GreenBackground extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Simple Web App',
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.lightGreenAccent, // Set the background color
      ),
      home: MyHomePage(), // Setting HomePage as the initial route
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold( // Scaffold widget for the home page
      body: Center(
        child: Text(
          'Flutter background demo page', // Displayed text in the page center
          style: TextStyle(fontSize:30.0),
        ),
      ),
    ); 
  }
}
Setting a background color using the scaffoldBackgroundColor property

Once we execute it, then we will have the output like this:

2. Using BoxDecoration

The second way to set the background color is to use BoxDecoration in the Container object. When developing a basic application, or one that does not incorporate Material design principlesMaterial Design principles are a set of guidelines that designers and developers follow to create consistent and visually appealing interfaces., this would be a suitable method.

import 'package:flutter/material.dart';

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

class GreenBackground extends StatelessWidget {
  // this is the root of the application
  @override
  Widget build(BuildContext context) {
    return   Container(
    width: 150,
    height: 100,
    decoration: BoxDecoration(
      color: Colors.lightGreenAccent,
      border: Border.all(
        color: Colors.blue,
        width: 10,
      ),
    ),
  );

  }
}
Setting a background color using BoxDecoration in the Container object
Explanation
  • Line 10: The widget is added to the GreenBackground class.

  • Line 15: The color of the background is added to the BoxDecoration decoration attribute of the Container object contained within the widget.

  • Line 16: The color of the border is added to the BoxDecoration decoration attribute of the Container object contained within the widget.

The screen is filled with a green color surrounded by a blue border. Once we execute it, then we will have the output like this:

3. Using Container

The third way to set the background color is to use the Container object itself.

Container(color: Colors.green)

Provide the Container widget color property with the required Color value or set the decoration property with the required background color value in it.

Background image

The background image in Flutter can be set using DecorationImage and BoxDecorationImage.

There are several steps in setting the background image using the DecorationImage method.

  1. Import the necessary packages.

import 'package:flutter/material.dart';
  1. Create a Container widget and set the decoration property to an object.

Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('Image_URL'),
fit: BoxFit.cover,
),
),
child: ...
)

Explanation

  • Lines 2–4: The BoxDecoration object has an image property set to the NetworkImage object of the background image file.

  • Line 5: The fit property is set to BoxFit.cover, so the image covers the entire area of the container.

Container(
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('Image_URL'),
fit: BoxFit.cover,
),
),
child: Column(
children: [
// add the widgets here
],
),
)
  1. Add the child widgets to the Container. These widgets will be displayed on top of the background image.

Explanation

  • Lines 8–11: We add child widgets to the container and will be displayed on top of the background image that has been added.

Note: Replace the image path in the code with your own image path or URL.

Run the following code to understand the usage of the DecorationImage property.

import 'package:flutter/material.dart';

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

class GreenBackground extends StatelessWidget {
  // this is the root of the application
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 50,
      height: 80,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: NetworkImage(
              'https://images.unsplash.com/photo-1528716321680-815a8cdb8cbe?q=80&w=2565&auto=format&f[…]3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D'),
          fit: BoxFit.contain,
        ),
        border: Border.all(
          color: Colors.blue,
          width: 10,
        ),
      ),
    );
  }
}
Setting a background color using the DecorationImage property

Once we execute it, then we will have the output like this:

Addition:

To set a gradient background in Flutter, you can use the BoxDecoration class with a gradient property. Here's how:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: GreenBackground(),
        ),
      ),
    );
  }
}

class GreenBackground extends StatelessWidget {
  // This is the custom container with gradient
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 200, // Adjusted width
      height: 300, // Adjusted height
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colors.blue, Colors.purple],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        border: Border.all(
          color: Colors.blue,
          width: 5,
        ),
        borderRadius: BorderRadius.circular(15), // Rounded corners
      ),
      child: Center(
        child: Text(
          'Hello, Gradient!',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}

The output will be like this:

Explanation:

  • The LinearGradient provides a transition between two colors from top-left to bottom-right.

  • You can also use RadialGradient or SweepGradient for circular or sweeping transitions.

This method is ideal when you want to create visually appealing transitions across multiple colors.

Conclusion

We have explored the methods for setting a background color and a background image in a Flutter application using the Dart programming language. The three methods for setting a background color are:

  • Set the background color for All Scaffolds by setting scaffoldBackgroundColor in ThemeData.

  • Use a decoration such as a BoxDecoration in the Container object.

  • Add the child widgets to the Container object.

The method for setting a background image is:

  • Use the DecorationImage and BoxDecoration classes.

Further learning

  • Explore different state management techniques like Provider, Riverpod, and Bloc to efficiently manage application state.

  • Learn to create smooth and interactive animations using Flutter's built-in animation libraries, like AnimatedBuilder and Hero.

  • Understand how to implement navigation and routing within your app using Navigator, named routes, and deep linking.

  • Dive into how to integrate Flutter with native Android and iOS features using platform channels for accessing device-specific functionality.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to run Flutter in background?

To run Flutter in the background:

  • On Android, use background services or task schedulers to handle actions like notifications, data syncing, or location tracking.

  • On iOS, configure background modes to enable tasks such as data fetching or push notifications.

  • Utilize cross-platform packages to simplify background operations and ensure compatibility across both Android and iOS.

This allows your Flutter app to perform tasks even when not actively in use.


How do I add wallpaper in Flutter?

To add a wallpaper in Flutter:

  • Utilize the BoxDecoration class to set a background image for UI elements.

  • Load images from online sources using NetworkImage, or use local images by including them in your project’s assets.

  • Ensure proper scaling and fitting of the image using BoxFit options like cover or contain.

  • Apply the background image to a Container or other suitable widgets in your app.

This will effectively set an image as a wallpaper or background in your Flutter app.


How do I add a background image in Flutter Flow?

To add a background image in Flutter Flow:

  • Select the widget or screen where you want to apply the background image.

  • Navigate to the Background section in the properties panel.

  • Choose the Image option to upload or link to an image file.

  • Adjust image settings such as fit (e.g., cover, contain) to ensure proper scaling and display of the background image.

This allows you to easily set a background image within Flutter Flow’s visual development environment.


Free Resources