注意:無特殊說明,Flutter版本及Dart版本如下:
- Flutter版本: 1.12.13+hotfix.5
- Dart版本: 2.7.0
CupertinoActionSheet組件是Cupertino(ios)風格底部彈出的提示框,一般情況下點擊按鈕彈出:
RaisedButton(
child: Text('點我'),
onPressed: () {
showCupertinoModalPopup(...);
},
)
showCupertinoModalPopup
方法是系統方法,其中的builder參數就是構建CupertinoActionSheet,用法如下:
showCupertinoModalPopup(
context: context,
builder: (context) {
return CupertinoActionSheet();
}
)
CupertinoActionSheet組件的actions屬性提供給用戶幾個選項,
CupertinoActionSheet(
title: Text('提示'),
message: Text('是否要刪除當前項?'),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text('刪除'),
onPressed: () {},
isDefaultAction: true,
),
CupertinoActionSheetAction(
child: Text('暫時不刪'),
onPressed: () {},
isDestructiveAction: true,
),
],
)
actions的子組件一般使用CupertinoActionSheetAction組件,CupertinoActionSheetAction組件向按鈕組件一樣,提供了子控件和onPressed回調,isDefaultAction
屬性設置爲true時,文字加粗,isDestructiveAction
屬性設置爲true時,文字顏色變爲紅色,效果如下:
如果想要一個和其他選項分開的組件,可以使用cancelButton
屬性,用法如下:
CupertinoActionSheet(
cancelButton: CupertinoActionSheetAction(
child: Text('取消'),
onPressed: () {},
),
)
效果如下:
那我們如何知道用戶選擇了哪個選項呢,我們需要在onPressed回調中返回不同的值,如下:
onPressed: () {
Navigator.of(context).pop('delete');
}
showCupertinoModalPopup方法是Future方法,用戶點擊了某一項時返回,完整代碼如下:
@override
Widget build(BuildContext context) {
return Center(
child: RaisedButton(
child: Text('點我'),
onPressed: () {
_showCupertinoActionSheet();
},
));
}
_showCupertinoActionSheet() async{
var result = await showCupertinoModalPopup(
context: context,
builder: (context) {
return CupertinoActionSheet(
title: Text('提示'),
message: Text('是否要刪除當前項?'),
actions: <Widget>[
CupertinoActionSheetAction(
child: Text('刪除'),
onPressed: () {
Navigator.of(context).pop('delete');
},
isDefaultAction: true,
),
CupertinoActionSheetAction(
child: Text('暫時不刪'),
onPressed: () {
Navigator.of(context).pop('not delete');
},
isDestructiveAction: true,
),
],
cancelButton: CupertinoActionSheetAction(
child: Text('取消'),
onPressed: () {
Navigator.of(context).pop('cancel');
},
),
);
});
print('$result');
}
通過result不同的值判斷用戶選擇了哪一項。