Flutter SnackBar
In mobile applications, SnackBar can be used to display a message to user for a brief period of time. After such default or specified period of time, the SnackBar is deleted.
By default, SnackBar slides from the bottom of the screen, stays there for some time, and then slides down till it disappears.
In this tutorial, we will learn how to display a SnackBar in the Scaffold of your Flutter Application.
Example: Flutter SnackBar
We need to have the current state of our Scaffold to display the SnackBar in it. To hold a global key for this Scaffold state, we shall create a final variable named _scaffoldKey and assign this to the key of Scaffold. So that, when we want to display a SnackBar, we can access the Scaffold current state using the _scaffoldKey.
main.dart
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_State createState() => _State();
}
class _State extends State<MyApp> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
void _showMessageInScaffold(String message){
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text(message),
)
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: Text('Flutter Tutorial - googleflutter.com'),
),
body: Center(
child: RaisedButton(
textColor: Colors.white,
color: Colors.blue,
child: Text('Show SnackBar'),
onPressed: (){
_showMessageInScaffold("Hello dear! I'm SnackBar.");
},
)
)
);
}
}
Screenshot
Summary
In this Flutter Tutorial, we learned how to display a SnackBar in Scaffold, with the help of well detailed example Flutter Application.