【问题标题】:Flutter WillPopScope works normally for me but when I navigate or push back to the same page it does not workFlutter WillPopScope 对我来说正常工作,但是当我导航或推回同一页面时它不起作用
【发布时间】:2019-11-26 09:50:00
【问题描述】:

我的问题是我有一个主页然后登录页面然后是主页,如果我在主页中按注销它应该导航我回到包含 willpopscope 的主页,我想要做的是防止用户在主页中按下后退按钮,以便应用程序在没有用户登录的情况下不会返回主页,问题是当我 Navigator.push 主页时 willpopscope 不起作用,所以每当我按下后退按钮让我回到主页。

我尝试改变 WillPopScope 的位置,如果我用它包裹整个小部件,它将永远无法为我工作

复制代码

//Main page:
class MainActivity extends StatefulWidget {
  final bool isWelcome;
  MainActivity(this.isWelcome);
  @override
  State<StatefulWidget> createState() {
    return OperateMainActivity(isWelcome);
  }
}

class OperateMainActivity extends State<MainActivity> {
  bool isWelcome = false;
  OperateMainActivity(this.isWelcome);
  @override
  Widget build(BuildContext context) {
    //print(isWelcome);
    return MaterialApp(
        home: MyHome(
      isWelcome: isWelcome,
    ));
  }
}

class myHome extends StatelessWidget
return Scaffold(
      body: Center(
          child: WillPopScope(
            onWillPop: () async => false,
        child: Container(....)


// Home page

Navigator.push(context,MaterialPageRoute(builder: (context) => MainActivity(false)));

//When pushing to main activity WillPopScope does not work

【问题讨论】:

    标签: android flutter dart


    【解决方案1】:

    WillPopScope 推送时不会被调用。这是合乎逻辑的行为,因为当您推送另一个视图时,它会超出堆栈中的当前视图。因此,当前视图永远不会弹出。

    如果您知道您的 MainActivity 在堆栈中的当前页面下方,您可以更改:

    Navigator.push(context,MaterialPageRoute(builder: (context) => MainActivity(false)));
    

    到:

    Navigator.pop(context); // This will make a call to onWillPop.
    

    更新:

    对于您想要实现的目标,您可以使用pushAndRemoveUntil

    Navigator.of(context).pushAndRemoveUntil(
      MaterialPageRoute(
        builder: (context) {
          return MainActivity();
        },
      ),
      (Route<dynamic> route) => false,
    );
    

    它将推送所需的页面并从堆栈中删除所有其他内容。

    【讨论】:

    • 还有其他解决方案吗,我的情况是,如果用户已登录,则会记住用户,因此视图堆栈永远不会包含主页,因为所有内容都被跳过并且显示的第一页是主页页面
    • 主页的用途是什么?您需要的是转到主页并从堆栈中删除所有其他内容?
    • 主页是通过应用程序登录或注册等导航的页面。一旦我登录,我就会进入主页,是的,我想进入主页并删除堆栈中的所有其他内容,就像我重新启动应用程序一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2021-02-07
    • 2019-10-08
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多