forked from vandadnp/flutter-tips-and-tricks
-
Notifications
You must be signed in to change notification settings - Fork 1
/
string-to-toast-in-flutter.dart
45 lines (41 loc) · 1.15 KB
/
string-to-toast-in-flutter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Want to support my work 🤝? https://buymeacoffee.com/vandad
extension Toast on String {
Future<void> showAsToast(BuildContext context,
{required Duration duration}) async {
final scaffold = ScaffoldMessenger.of(context);
final controller = scaffold.showSnackBar(
SnackBar(
content: Text(this),
backgroundColor: const Color(0xFF24283b),
behavior: SnackBarBehavior.floating,
elevation: 2.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
);
await Future.delayed(duration);
controller.close();
}
}
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
onPressed: () => 'Hello, World!'.showAsToast(
context,
duration: const Duration(seconds: 2),
),
child: const Text('Show the snackbar'),
),
),
);
}
}