How to set Background Image for AppBar in Flutter

AppBar is one of the most used widgets in Flutter. It is also highly customizable. In this Flutter tutorial, let’s learn how to show an AppBar with an image background.

First, you must add an image to your project and mention it in the pubspec.yaml file. The AppBar has a property named flexibleSpace and it helps us to add widgets to customize. We make use of BoxDecoration, DecorationImage, and AssetImage to show an image as the background.

See the code snippet given below.

AppBar(
          title: const Text(
            'Flutter AppBar Image Background',
          ),
          flexibleSpace: Container(
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('images/sky.jpg'), fit: BoxFit.fill)),
          ),
        ),

Following is the output.

flutter appbar image background

Following is the complete code for reference.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            'Flutter AppBar Image Background',
          ),
          flexibleSpace: Container(
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('images/sky.jpg'), fit: BoxFit.fill)),
          ),
        ),
        body: const Center(
            child: Text('Flutter AppBar image background tutorial')));
  }
}

I hope this Flutter AppBar image background example is helpful for you.

Similar Posts

Leave a Reply