【问题标题】:WillPopScope cannot detect that the Android back button has been pressedWillPopScope 无法检测到 Android 后退按钮已被按下
【发布时间】:2021-01-19 22:41:57
【问题描述】:

前提・我想达到的目标

我打算在按下 Android 后退按钮时使用 WillPopScope 禁用它。

问题・错误信息

在 WillPopScope 中封闭 Scaffold 并按下 Android 后退按钮不会执行 WillPopScope 中设置的功能。

对应源码

Future<bool> onWillPopScope() async {
    print('on');
    return false;
}

Widget build(BuildContext context) {
 return ChangeNotifierProvider<xxxModel>(
  create:(_) => xxxModel(),
  child: Stack(
   children<Widget>[
    WillPopScope(
     onWillPop: onWillPopScope,
     child: Scaffold(
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     )
    ),
    Consumer<xxxModel>(
     ~~~~~~~~~~~~~~~~~~~~
    ),
   ],
  ),
 );
}

我尝试了什么

我更改了 WillPopScope 的位置,但它不起作用。

补充信息(FW/工具版本等)

・Flutter 1.17.5

・飞镖2.8.4

【问题讨论】:

    标签: android flutter dart


    【解决方案1】:

    如果您使用的是 Navigationappbar,请尝试下面的 pprocess,

     Future<bool> _onBackPressed() {
            return showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('Are you sure?'),
              content: new Text('Do you want to exit an App'),
              actions: <Widget>[
                new GestureDetector(
                  onTap: () => Navigator.of(context).pop(false),
                  child: Text("NO"),
                ),
                SizedBox(height: 16),
                new GestureDetector(
                  onTap: () {
                    exit(0);
                  },
                  child: Text("YES"),
                ),
              ],
            ),
          ) ??
          false;
        }
    
      Widget build(BuildContext context) {
       return Scaffold(
       key: _globalKey,
       body: WillPopScope(
          child: _getBody(_currentIndex),//your widget list index wise
          onWillPop: () async {
            if (_globalKey.currentState.isDrawerOpen) {
              Navigator.pop(context); // closes the drawer if opened
              return Future.value(false); // won't exit the app
            } else {
              //only back to o index
              if (_currentIndex == 0) _onBackPressed();
              //return true;
              setState(() {
                _currentIndex = 0;
              });
              return false;
              _onBackPressed();
              // return Future.value(true); // exits the app
            }
          },
        ),
       
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 2017-12-23
      • 2020-06-02
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      相关资源
      最近更新 更多