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

我编写了三页应用程序的简单代码,在第三页中,当它使用“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 时,它不会返回到第二页,但也不会更改文本


哔哔one
浏览 193回答 2
2回答

青春有我

我猜你为什么在使用 Navigator.push 更改页面之前使用设置状态方法。SetState 应该用于更改当前所在页面上的数据状态,而不是用作“全局”数据存储。我建议你几个选择:使用所有页面共享的“顶级”提供程序并更新其值:Provider使用本地数据库SQLite

小怪兽爱吃肉

您需要为每个具有构建功能的单独的类创建上下文,这样每个页面的上下文都是新的,这样您就必须创建有状态的类,然后创建该页面的另一个类
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript