Flutter 对话框

定义弹出对话框方法

Flutter对话框的使用主要使用两个组件 showDialogAlertDialog, 使用 showDialog 创建一个 AlertDialog,showDialog返回的是一个可为空的Future。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 显示对话框
Future<bool?> showAppAlertDialog(context) {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('确定提交'),
content: const Text('提交以后无法恢复,确定提交吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('确定'),
),
],
// 默认为右对齐
actionsAlignment: MainAxisAlignment.center,
),
);
}

显示对话框

调用对话框的方法需要定义为异步方法。

1
2
3
4
5
6
7
8
TextButton(
onPressed: () async {
// 显示对话框
final result = await showAppAlertDialog(context);
print('showAppAlertDialog: $result');
},
child: const Text('提交'),
),

完整代码

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
46
47
48
49
50
51
52
53
54
55
import 'package:flutter/material.dart';

/// 底部弹出面板
class AppBottomSheet extends StatelessWidget {
const AppBottomSheet({Key? key}) : super(key: key);

// 显示对话框
Future<bool?> showAppAlertDialog(context) {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('确定提交'),
content: const Text('提交以后无法恢复,确定提交吗?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('取消'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('确定'),
),
],
actionsAlignment: MainAxisAlignment.center,
),
);
}

@override
Widget build(BuildContext context) {
return Container(
height: 350,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.background,
boxShadow: const [
BoxShadow(
color: Colors.black12,
offset: Offset(0, -20),
blurRadius: 30,
),
],
),
child: Center(
child: TextButton(
onPressed: () async {
// 显示对话框
final result = await showAppAlertDialog(context);
print('showAppAlertDialog: $result');
},
child: const Text('提交'),
),
),
);
}
}