为了账号安全,请及时绑定邮箱和手机立即绑定

flutter setState 在使用 Navigator.push 时弹出页面

flutter setState 在使用 Navigator.push 时弹出页面

哔哔one 2023-09-14 20:19:53
我编写了三页应用程序的简单代码,在第三页中,当它使用“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 时,它不会返回到第二页,但也不会更改文本
查看完整描述

2 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

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

我建议你几个选择:

  • 使用所有页面共享的“顶级”提供程序并更新其值:Provider

  • 使用本地数据库SQLite

查看完整回答
反对 回复 2023-09-14
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

您需要为每个具有构建功能的单独的类创建上下文,这样每个页面的上下文都是新的,这样您就必须创建有状态的类,然后创建该页面的另一个类



查看完整回答
反对 回复 2023-09-14
  • 2 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信