text
stringlengths
1
372
);
<code_end>
<topic_end>
<topic_start>
2. display a SnackBar
with the scaffold in place, display a SnackBar.
first, create a SnackBar, then display it using ScaffoldMessenger.
<code_start>
const snackBar = SnackBar(
content: Text('Yay! a SnackBar!'),
);
// find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
<code_end>
info note
to learn more, watch this short widget of the week video on the ScaffoldMessenger widget:
<topic_end>
<topic_start>
3. provide an optional action
you might want to provide an action to the user when
the SnackBar is displayed.
for example, if the user accidentally deletes a message,
they might use an optional action in the SnackBar to recover
the message.
here’s an example of providing
an additional action to the SnackBar widget:
<code_start>
final snackBar = SnackBar(
content: const Text('Yay! a SnackBar!'),
action: SnackBarAction(
label: 'undo',
onPressed: () {
// some code to undo the change.
},
),
);
<code_end>
<topic_end>
<topic_start>
interactive example
info note
in this example, the SnackBar displays when a user taps a button.
for more information on working with user input,
see the gestures section of the cookbook.
<code_start>
import 'package:flutter/material.dart';
void main() => runApp(const SnackBarDemo());
class SnackBarDemo extends StatelessWidget {
const SnackBarDemo({super.key});
@override
widget build(BuildContext context) {
return MaterialApp(
title: 'snackbar demo',
home: scaffold(
appBar: AppBar(
title: const Text('SnackBar demo'),
),
body: const SnackBarPage(),
),
);
}
}
class SnackBarPage extends StatelessWidget {
const SnackBarPage({super.key});
@override
widget build(BuildContext context) {
return center(
child: ElevatedButton(
onPressed: () {
final snackBar = SnackBar(
content: const Text('Yay! a SnackBar!'),
action: SnackBarAction(
label: 'undo',
onPressed: () {
// some code to undo the change.
},
),
);
// find the ScaffoldMessenger in the widget tree
// and use it to show a SnackBar.
ScaffoldMessenger.of(context).showSnackBar(snackBar);
},
child: const Text('Show SnackBar'),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
using actions and shortcuts
this page describes how to bind physical keyboard events to actions in the user
interface. for instance, to define keyboard shortcuts in your application, this
page is for you.
<topic_end>
<topic_start>
overview
for a GUI application to do anything, it has to have actions: users want to tell
the application to do something. actions are often simple functions that