
到目前为止,你已经可以:
但如果你的 App 没有任何 操作反馈,用户体验会非常差:
Flutter 提供了 SnackBar / AlertDialog / Toast 来解决这些问题。
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('操作成功')),
);
📌 特点:
ElevatedButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('保存成功'),
duration: Duration(seconds: 2),
),
);
},
child: Text('显示 SnackBar'),
)
📌 参数说明:
content → 显示内容duration → 显示时长backgroundColor → 背景色可自定义ElevatedButton(
onPressed: () async {
await Future.delayed(Duration(seconds: 2));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('异步操作完成')),
);
},
child: Text('异步提示'),
)
📌 异步完成后提示用户操作结果 → UX 更友好
SnackBar(
content: Text('操作成功'),
duration: Duration(seconds: 3),
backgroundColor: Colors.green,
action: SnackBarAction(
label: '撤销',
onPressed: () {
print('用户点击撤销');
},
textColor: Colors.white,
),
)
action → 提供按钮操作,例如撤销、重试backgroundColor → 自定义颜色showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('提示'),
content: Text('确定要删除吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('取消'),
),
TextButton(
onPressed: () {
print('删除操作');
Navigator.pop(context);
},
child: Text('确定'),
),
],
);
},
);
📌 特点:
组件 | 适用场景 | 特点 |
|---|---|---|
SnackBar | 提示操作结果 | 非阻塞,短时显示 |
AlertDialog | 重要确认 / 提醒 | 阻塞用户操作,需要响应 |
假设表单提交后:
if (_formKey.currentState!.validate()) {
// 异步提交
await Future.delayed(Duration(seconds: 1));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('提交成功')),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('请检查表单信息')),
);
}
📌 用户体验大幅提升:
❌ ScaffoldMessenger 用错 context → SnackBar 不显示 ❌ 没设置 duration → 默认太短或太长 ❌ 弹窗内直接调用异步操作导致关闭异常 ❌ 过度使用弹窗 → 用户疲劳
📌 建议:
你已经学会:
📌 到这里为止:
你的 App 已经具备“用户友好提示能力”
SnackBar 快速提示 AlertDialog 重要确认 用户操作立即反馈 = 好体验
《Flutter 零基础入门(三十八):网络请求实战 http / dio —— 获取列表与刷新 UI》
下一篇我们将学习:
🚀 开始真正获取远程数据