Huseyn
Huseyn

Reputation: 412

Material Banner in flutter 2.5

How do I implement a MaterialBanner in Flutter 2.5 ?

Like this :

enter image description here

Upvotes: 7

Views: 4294

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267554

To show MaterialBanner:

Just call this method:

void showMaterialBanner() {
  final materialBanner = MaterialBanner(
    content: Text('Good Morning'),
    actions: [
      TextButton(
        onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
        child: Text('Dismiss'),
      ),
    ],
  );
  ScaffoldMessenger.of(context).showMaterialBanner(materialBanner);
}

To hide MaterialBanner:

You can hide it in 3 ways:

  1. With animation:

    ScaffoldMessenger.of(context).hideCurrentMaterialBanner();
    
  2. With animation:

    final controller = ScaffoldMessenger.of(context).showMaterialBanner(materialBanner);
    controller.close();
    
  3. Without animation:

    ScaffoldMessenger.of(context).removeCurrentMaterialBanner();
    

To hide all existing and show a new one:

ScaffoldMessenger.of(context)
  ..hideCurrentMaterialBanner() // or removeCurrentMaterialBanner
  ..showMaterialBanner(materialBanner);

Upvotes: 6

Guillaume Roux
Guillaume Roux

Reputation: 7308

First ensure you are using Flutter v2.5.

> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.5.0, on Microsoft Windows [version 10.0.19043.1165], locale fr-FR)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1)
[√] Connected device (2 available)

Then simply call the method ScaffoldMessenger.of(context).showMaterialBanner() when you have a Scaffold in your widget tree.

The following code is taken from the article "What's new in Flutter 2.5" and correspond to the image you are showing:

class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: const Text('The MaterialBanner is below'),
        ),
        body: Center(
          child: ElevatedButton(
            child: const Text('Show MaterialBanner'),
            onPressed: () => ScaffoldMessenger.of(context).showMaterialBanner(
              MaterialBanner(
                content: const Text('Hello, I am a Material Banner'),
                leading: const Icon(Icons.info),
                backgroundColor: Colors.yellow,
                actions: [
                  TextButton(
                    child: const Text('Dismiss'),
                    onPressed: () => ScaffoldMessenger.of(context)
                        .hideCurrentMaterialBanner(),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
}

Upvotes: 10

Related Questions