Here we will use ScaffoldMessenger, showSnackBar and snackBar together to show a message on button press from the bottom.
Flutter ScaffoldMassenger is works for like showing pop up message. ScaffoldMassenger shows, hide and remove snackBar.
The MaterialApp
widget provides a root ScaffoldMessenger
. If you show a SnackBar
using the root ScaffoldMessenger
, it becomes possible for all descendant Scaffold
s to receive the SnackBar
. However, you can control which Scaffold
s can receive the SnackBar
.
void main() async {
runApp(MyApp( ));
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primaryColor: Colors.blue,
fontFamily: "Lato",
),
home: Scaffold(
backgroundColor: Colors.red,
body: Center(
child: Message(),
),
),
);
}
}
class Message extends StatefulWidget {
const Message({Key? key}) : super(key: key);
@override
State<Message> createState() => _MessageState();
}
class _MessageState extends State<Message> {
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text("press"),
onPressed: (){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('back press again to exit', style: TextStyle(color: Colors.white)),
behavior: SnackBarBehavior.floating,
backgroundColor: Colors.green,
duration: Duration(seconds: 2),
margin: EdgeInsets.all(5),
));
},
);
}
}
For this to work we use a stateful or stateless widget.
We need to remember to use behavior: SnackBarBehavior.floating,