UPDATE: Scaffold.of(context).showSnackBar
is deprecated in Flutter 2.0.0 (stable)
You can access the parent ScaffoldMessengerState
using ScaffoldMessenger.of(context)
.
Then do something like
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Sending Message"),
));
Snackbars are the official "Toast" from material design. See Snackbars.
Here is a fully working example:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Home(),
);
}
}
class Home extends StatelessWidget {
const Home({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Snack bar'),
),
body: Center(
child: RaisedButton(
onPressed: () => _showToast(context),
child: const Text('Show toast'),
),
),
);
}
void _showToast(BuildContext context) {
final scaffold = ScaffoldMessenger.of(context);
scaffold.showSnackBar(
SnackBar(
content: const Text('Added to favorite'),
action: SnackBarAction(label: 'UNDO', onPressed: scaffold.hideCurrentSnackBar),
),
);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…