11.9 C
New York
Wednesday, November 22, 2023

Flutter: Set an image background for a Container

To set an image background for a Container widget in Flutter, we set its decoration property like this:

decoration: const BoxDecoration(
       image: DecorationImage(
              image: NetworkImage(/*...*/),
              fit: BoxFit.cover,
              repeat: ImageRepeat.noRepeat,
       ),
),

You can use either NetworkImage or AssetImage. If you have a plan to use AssetImage, you need to declare the images you are going to use in your pubspec.yaml file. If you arenÂ’t familiar to this stuff, see the article using Local Images in Flutter.Advertisements

A complete example

Preview:

The beautiful background here is from Pixabay, a wonderful site to get free images.

The full code in main.dart:

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      theme: ThemeData.dark(),
      home: const HomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: Center(
        child: Container(
          alignment: Alignment.center,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(
                  'https://www.kindacode.com/wp-content/uploads/2022/02/beach.jpeg'),
              fit: BoxFit.cover,
              repeat: ImageRepeat.noRepeat,
            ),
          ),
          child: Container(
              padding: const EdgeInsets.all(25),
              color: Colors.black45,
              child: const Text(
                'My dog likes watching Netflix',
                style: TextStyle(color: Colors.white, fontSize: 24),
              )),
        ),
      ),
    );
  }
}

AdvertisementsHope this helps. Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles