首页 > 解决方案 > Flutter setState 在使用 Navigator.push 时弹出页面,而在使用 Navigator.of 时它根本不起作用

问题描述

我编写了三页应用程序的简单代码,在第三页中,当它使用“SetState”时,它返回到第二页,但仅在第三页发生,当我在第二页中使用“setState”时,它工作正常。我还尝试使用“Navigator.of.push”在页面之间导航,但是 setState 在这里没有做任何事情,这是我的代码示例

String check="go to next page";
String check2="state1";
Widget page3()
{
  
  return return  FlatButton(
      child:Text(check2)
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(18.0),
          side: BorderSide(color: Colors.blue[100])),
      color: Colors.white,
      onPressed: (){
       setState((){check2="state3"});
          
         });
 }
Widget Profile()
{
 return  FlatButton(
      child:Text(check)
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(18.0),
          side: BorderSide(color: Colors.blue[100])),
      color: Colors.white,
      onPressed: (){
       setState((){check2="state3"});
       Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => page3()),
          )      
         });
}
Widget Biuld(BuildContext context)
{
 return return Scaffold(
  appBar: AppBar(
    // Here we take the value from the MyHomePage object that was created by
    // the App.build method, and use it to set our appbar title.
    title: Text(widget.title),
  ),
  body:
   FlatButton(
      child:Text("press to start")
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(18.0),
          side: BorderSide(color: Colors.blue[100])),
      color: Colors.white,
      onPressed: (){
       Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => profile()),
          ); 
               
         }));
 }

我得到的结果是,当按下第一个按钮时,它转到第 2 页,当我按下第二个按钮时,它更改第二个按钮文本并转到第三页,但是当我按下第三页上的按钮时,它又回到第二页。使用 navgitor.of 时,它不会返回到第二页,但也不会更改文本

标签: javascriptandroidflutter

解决方案


我猜你为什么在使用 Navigator.push 更改页面之前使用 set state 方法。SetState 应该用于更改您当前所在页面上的数据状态,而不是用作“全局”数据存储。

我建议你几个选择:

  • 使用所有页面共享的“顶级”提供程序并更新其值:提供程序
  • 使用本地数据库SQLite

编辑:可能这可能会帮助您使用提供者管理状态


推荐阅读