Flutter Widgets 之 CupertinoActionSheet

注意:無特殊說明,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不同的值判斷用戶選擇了哪一項。

今天的文章對大家是否有幫助?如果有,請在文章底部留言和點贊,以表示對我的支持,你們的留言、點贊和轉發關注是我持續更新的動力!

更多相關閱讀:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章