We are going to learn how create snackbars in Flutter. We use snackbars to notifyier users something within an app.
Lets go to see the most simple SnackBar. First, we build MyApp class. The build method returns a MaterialApp class. The home of MaterialApp is a Scaffold, wich body is SnackBarPage class.
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Snackbar',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: Scaffold(
appBar: AppBar(
title: Text('Flutter SnackBar'),
),
body: SnackbarPage(),
),
);
}
}
The class SnackBarPage has our SnackBar. I have developed two versions. The first is the most simple, it comes from down to up. It don´t has margin. If we want it has margin, it need SnackBarBehavior.floating.

class SnackbarPage extends StatelessWidget {
const SnackbarPage();
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
final snackBar = SnackBar(
content: const Text(
'Hi, this is a SnackBar!',
// style: TextStyle(color: Colors.black),
),
action: SnackBarAction(
label: 'Close',
onPressed: () {
// No code, only warning.
},
),
backgroundColor: Colors.grey,
duration: Duration(seconds: 1),
behavior: SnackBarBehavior.floating,
margin: EdgeInsets.only(left: 20, right: 20, bottom: 50),
elevation: 5,
);
// Find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: const Text('Show SnackBar: behaviour, margin'),
),
ElevatedButton(
onPressed: () {
final snackBar = SnackBar(
content: const Text(
'Hi, this is a SnackBar!',
// style: TextStyle(color: Colors.black),
),
action: SnackBarAction(
label: 'Close',
onPressed: () {
// No code, only warning.
},
),
backgroundColor: Colors.grey,
duration: Duration(seconds: 1),
elevation: 5,
);
// Find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: const Text('Show SnackBar'),
),
],
),
);
}
}
Here we have put two buttons that show the different types of SnackBar that we can create using or not the margin and behavior properties.
In the video you can see the operation of each one of them.
We can decide how long our SnackBar is shown by modifying the duration property.
Deja una respuesta