Flutter 底部弹出面板的使用

定义底部弹出面板

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
import 'package:flutter/material.dart';

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

@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: const Center(
child: Text('AppBottomSheet'),
),
);
}
}

使用底部弹出面板

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
import 'package:flutter/material.dart';
import 'package:flutter_xb2/app/components/app_bottom_sheet.dart';

/// 分享漂浮按钮
class AppFloatingActionButton extends StatefulWidget {
const AppFloatingActionButton({Key? key}) : super(key: key);

@override
State<AppFloatingActionButton> createState() => _AppFloatingActionButtonState();
}

class _AppFloatingActionButtonState extends State<AppFloatingActionButton> {
/// 是否正在显示底部面板
bool isBottomSheetShown = false;

Icon floatingActionButtonIcon() {
return isBottomSheetShown ? const Icon(Icons.close) : const Icon(Icons.share_outlined);
}

@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: () {
// 关闭底部面板
if (isBottomSheetShown) {
return Navigator.pop(context);
}

// 显示底部面板
final bottomSheetController = showBottomSheet(
context: context,
builder: (context) => const AppBottomSheet(),
);

setState(() {
isBottomSheetShown = true;
});

// 关闭底部面板之后的事件
bottomSheetController.closed.then(
(value) => {
setState(() {
isBottomSheetShown = false;
})
},
);
},
child: floatingActionButtonIcon(),
backgroundColor: Colors.black87,
foregroundColor: Colors.white70,
);
}
}