Last Updated on 2021-10-25 by Clay
We often use the SnackBar message component in Flutter Apps to display the remind messages.
After all, it is difficult to use the print()
function to interact with user, and it is also difficult for making a new widget for message displaying.
In Flutter, it is actually very easy to display SnackBar messages, just use the following component:
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Sending Message"),
)
);
The following is the complete sample code.
Sample Code
import 'package:flutter/material.dart';
void main() => runApp(SnackBarDemo());
class SnackBarDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SnackBarPage(),
),
);
}
}
class SnackBarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
child: Text("Show Toast"),
onPressed: () {
final scaffold = ScaffoldMessenger.of(context);
final snackBar = SnackBar(
content: Text("This is a Toast Component"),
action: SnackBarAction(
label: 'CANCEL',
onPressed: () {
scaffold.removeCurrentSnackBar();
},
),
);
// Show
scaffold.showSnackBar(snackBar);
},
),
);
}
}
Output:
As you can see, if we click the Show Toast button, A SnackBar will show on the bottom of the screen.
The above is a simple introduction to SnackBar message component in Flutter. Hope we have fun in the development.
References
- https://stackoverflow.com/questions/45948168/how-to-create-toast-in-flutter
- https://flutter.dev/docs/cookbook/design/snackbars