SnackBar is used to show a message to user for a brief period of time. Also, you can provide an action label in SnackBar to perform an action when pressed on it.
In this tutorial, we will learn how to provide an Action label in SnackBar.
Following is a quick syntax to provide an Action inside SnackBar.
SnackBar(
content: Text(message),
action: SnackBarAction(
label: 'Undo', // or some operation you would like
onPressed: () {
// this block runs when label is pressed
},
),
)
SnackBar has a property called action that accepts a SnackBarAction widget.
SnackBarAction has label which gets displayed like a secondary button with no background color or border. But when pressed, you can run some code using onPressed() property as shown in the above code snippet.
Example: SnackBar Action
In this example, we shall implement a SnackBar that shows a message. Also, we have an action which when pressed, prints something to the console. You may place code in place of this print statement as per your application requirement.
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){
try {
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: Text(message),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
// some code
print('Action in Snackbar has been pressed.');
},
),
)
);
} on Exception catch (e, s) {
print(s);
}
}
@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 an action in SnackBar, with the help of well detailed example Flutter Application.