There is a better and cleaner way to display a fluttering snack bar. I found this the hard way and sharing, so maybe this is useful for someone else.
No need to change in the main part of the application
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'MyApp', theme: new ThemeData( primarySwatch: Colors.orange), home: new MainPage()); } }
The page status code is where everything will change.
We know that Flutter provides Scaffold.of(context).showSnackBar
. However, the context should be the context of the descendant of the scaffold, and not the context of the scaffold. To avoid errors, we need to use the BuildContext for the Scaffold body and save it in a variable, as shown below.
class MainPageState extends State<MainPage> { BuildContext scaffoldContext; @override Widget build(BuildContext context) { return new Scaffold( backgroundColor: Colors.grey, appBar: new AppBar( title: const Text(APP_TITLE), ), body: new Builder(builder: (BuildContext context) { scaffoldContext = context; return new Center( child: new Text('Hello World', style: new TextStyle(fontSize: 32.0)), ); })); } void createSnackBar(String message) { final snackBar = new SnackBar(content: new Text(message), backgroundColor: Colors.red);
Now you can call this function from anywhere in the world and it will display a snack bar. For example, I use it to display internet connection messages.
source share