嗶嗶one
2023-09-14 20:19:53
我編寫(xiě)了三頁(yè)應(yīng)用程序的簡(jiǎn)單代碼,在第三頁(yè)中,當(dāng)它使用“SetState”時(shí),它返回到第二頁(yè),但僅在第三頁(yè)中發(fā)生,當(dāng)我在第二頁(yè)中使用“setState”時(shí),它工作正常。我還嘗試使用“Navigator.of.push”在頁(yè)面之間導(dǎo)航,但 setState 只是沒(méi)有執(zhí)行任何操作,這里是我的代碼示例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()), ); })); }我得到的結(jié)果是,當(dāng)按下第一個(gè)按鈕時(shí),它會(huì)轉(zhuǎn)到第2頁(yè),當(dāng)我按下第二個(gè)按鈕時(shí),它會(huì)更改第二個(gè)按鈕文本并轉(zhuǎn)到第三頁(yè),但是當(dāng)我按下第三頁(yè)上的按鈕時(shí),它會(huì)返回到第二頁(yè)。使用 navgitor.of 時(shí),它不會(huì)返回到第二頁(yè),但也不會(huì)更改文本
2 回答

青春有我
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
我猜你為什么在使用 Navigator.push 更改頁(yè)面之前使用設(shè)置狀態(tài)方法。SetState 應(yīng)該用于更改當(dāng)前所在頁(yè)面上的數(shù)據(jù)狀態(tài),而不是用作“全局”數(shù)據(jù)存儲(chǔ)。
我建議你幾個(gè)選擇:
使用所有頁(yè)面共享的“頂級(jí)”提供程序并更新其值:Provider
使用本地?cái)?shù)據(jù)庫(kù)SQLite

小怪獸愛(ài)吃肉
TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
您需要為每個(gè)具有構(gòu)建功能的單獨(dú)的類(lèi)創(chuàng)建上下文,這樣每個(gè)頁(yè)面的上下文都是新的,這樣您就必須創(chuàng)建有狀態(tài)的類(lèi),然后創(chuàng)建該頁(yè)面的另一個(gè)類(lèi)
添加回答
舉報(bào)
0/150
提交
取消