最终实现效果如图片所示,分布演示了基础的,全屏的和自定义的底部弹窗形式。
代码结构
在消息页面 message.dart 中,使用 Column
组件构建了三个按钮,点击每个按钮调用不同的底部弹窗显示。这部分代码不展示,核心注意的方式是按钮的 onPressed
响应方法,需要使用 async
修饰,这是因为 ModalBottomSheet
的返回结果是一个 Future
对象,需要通过 await
来获取返回结果。
onPressed: () async {
int selectedIndex = await _showCustomModalBottomSheet(context, _options);
print(“自定义底部弹层:选中了第$selectedIndex个选项”);
},
//…
基本使用
基本使用对于全屏和默认只差一个参数,演示代码中,我们使用了一组模拟的数据构建选项数据,然后再传给显示底部弹窗的方法,实际这组数据大部分是从后台获取的。当 isScrollControlled
是 true
时,则是全屏弹窗,默认是 false
。
Future _showBasicModalBottomSheet(context, List options) async {
return showModalBottomSheet(
isScrollControlled: false,
context: context,
builder: (BuildContext context) {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(options[index]),
o