Home > database >  Applying correct theme to SnackBar when using ScaffoldMessenger GlobalKey
Applying correct theme to SnackBar when using ScaffoldMessenger GlobalKey

Time:07-30

In order to have a globally available method for showing snackbars, i created a Riverpod provider for the ScaffoldMessenger, as it can be found in some examples on the internet:

final scaffoldMessengerKeyProvider = Provider((ref) => 
      GlobalKey<ScaffoldMessengerState>());
final scaffoldMessengerProvider = Provider((ref) => 
      ref.watch(scaffoldMessengerKeyProvider).currentState!);

return MaterialApp.router(
      theme: AppTheme.lightTheme,
      darkTheme: AppTheme.darkTheme,

      scaffoldMessengerKey: ref.watch(scaffoldMessengerKeyProvider),
      ...
    );

This allows me to show snackbars from anywhere by calling:

widgetRef.read(scaffoldMessengerProvider).showSnackBar(
      SnackBar(
            content: Text('Hi, i am a SnackBar'),
      ),
);

Showing the snackbar works fine, but the theme that is being applied to those snackbars seems to be the blue default theme. How could I apply my own Themes (AppTheme.lightTheme / AppTheme.darkTheme) to this ScaffoldMessenger or just the snackbars? Is there a clean way of doing this, that i'm not seeing?

CodePudding user response:

I think the cleanest way to do it is inside your lightTheme and darkTheme and apply the desired Theme.

Example:

static final darkTheme = ThemeData(
snackBarTheme: const SnackBarThemeData(
  actionTextColor: Colors.red,
  backgroundColor: Colors.black,
  contentTextStyle: TextStyle(color: Colors.white),
  elevation: 20
),
  • Related