天天看點

Flutter系列之showDialog攔截傳回鍵

Flutter中彈出對話框是使用showDialog函數,如果想攔截傳回鍵,不想其點選傳回鍵的時候消失,

就要嵌套一層WillPopScope,示例代碼如下:

showDialog(
      context: context,
      barrierDismissible: false,//點選外部遮罩區域是否可以關閉dialog
      builder: (context) {
        return WillPopScope(
          onWillPop: () async => false,//關鍵代碼
          child: Dialog(
            backgroundColor: Colors.transparent,
            insetPadding: EdgeInsets.zero,
            child: child,
          ),
        );
      },
    );
           

在Dialog的外面再嵌套一層WillPopScope,并将onWillPop設為false即可