一般 Toast
是由上方彈出,而 SnakeBar
是由下方彈出。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
SnakeBar
顯示由下方彈出的 toast
SnakeBar
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
const Home({super.key});
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('SnackBar'),
);
var elevatedButton = ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('This is a SnackBar!'),
duration: Duration(seconds: 2),
),
);
},
child: const Text('Show SnackBar'),
);
var body = Center(
child: elevatedButton,
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 11
var elevatedButton = ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('This is a SnackBar!'),
duration: Duration(seconds: 2),
),
);
},
child: const Text('Show SnackBar'),
);
SnackBar
content
:顯示內容duration
:持續時間
Conclusion
SnackBar
屬於 Feedback 類 widget,因此必須使用ScaffoldMessenger.of(context).showSnackBar()
顯示SnackBar