Skip to content

Instantly share code, notes, and snippets.

@dumazy
Created August 27, 2024 17:38
Show Gist options
  • Save dumazy/fdcb7aae2bc27a7bd02c6ca28d36aef8 to your computer and use it in GitHub Desktop.
Save dumazy/fdcb7aae2bc27a7bd02c6ca28d36aef8 to your computer and use it in GitHub Desktop.
ScaffoldMessenger theming issue
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
final _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
void showThemedSnackBar() {
final messenger = _scaffoldMessengerKey.currentState!;
final context = _scaffoldMessengerKey.currentContext!;
// Theme is not the `MaterialApp.theme` as below because
// it is not an ancestor of the default ScaffoldMessenger
final theme = Theme.of(context);
final snackBar = SnackBar(
content: Text(
'Themed message',
style: TextStyle(
color: theme.colorScheme.onPrimary,
),
),
backgroundColor: theme.colorScheme.primary,
);
messenger.showSnackBar(snackBar);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
// Remove scaffoldMessengerKey below for the workaround
scaffoldMessengerKey: _scaffoldMessengerKey,
theme: ThemeData(
colorScheme: ColorScheme.light(
primary: Colors.red,
onPrimary: Colors.yellow,
),
),
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: showThemedSnackBar,
child: Text('Show snackbar'),
),
),
),
// Workaround (remove the MaterialApp.scaffoldMessengerKey above)
// builder: (_, child) => ScaffoldMessenger(
// key: _scaffoldMessengerKey,
// child: child!,
// ),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment