Home > front end >  Show custom widget with ScaffoldMessenger
Show custom widget with ScaffoldMessenger

Time:05-22

I’d like to have a widget in my application that operates much in the same way as a MaterialBanner with ScaffoldMessenger. But I’d like to customize the appearance of banner.

Is there a way that I can customize the appearance of MaterialBanner? In my initial experimentation I thought of extending it, but in the end I found that wasn’t really going to work. Also for a brief second I thought thought type casting a custom widget in my call to showMaterialBanner might work, but quickly ruled that out.

CodePudding user response:

A MaterialBanner is already customizable. Place your desired widget in the content param or actions list.

ScaffoldMessenger.of(context).showMaterialBanner(
  MaterialBanner(
    content: const Text('This is a MaterialBanner'), // <- This can be whatever you want
    actions: <Widget>[
      TextButton(
        onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
        child: const Text('DISMISS'), 
      ), // <- So can these
    ],
  ),
);

CodePudding user response:

you can change styles of MaterialBanner ( outer widget ) in your app theme :

MaterialApp(
  .
  .
  theme: ThemeData(
    .
    .
    .
    bannerTheme: MaterialBannerThemeData(
      backgroundColor: ,
      contentTextStyle: ,
      elevation: ,
      leadingPadding: ,
    ),
  ),
);

and if you want change structure of inner widget you can pass any widget to content :

MaterialBanner(
  content: Row(
    children: const[
      Icon(Icons.check),
      Expanded(
        child: Text('This is a MaterialBanner'),
      ),
    ],
  ),
  actions: [
    TextButton(
      onPressed: () => ScaffoldMessenger.of(context).hideCurrentMaterialBanner(),
      child: const Text('DISMISS'),
    ),
  ],
);
  • Related