[英]How to pass a variable reference between different routes?
我正在編寫帶有菜單,游戲和選項路線的簡單Gamebook游戲。 在選項路徑中,有一個按鈕,按下該按鈕應刪除所有保存的游戲。
目前,我正在從SharedPreferences啟動應用程序時加載已保存的游戲。 加載它們后,我立即設置了布爾_savedGame
,我在菜單路徑的'Continue'
按鈕和選項路徑的“刪除保存的游戲”按鈕中使用它們來激活或停用它們。 整個問題是-我不知道如何從選項路由更改菜單路由中的變量。 當我創建選項路由時,我給它_savedGame
以便它知道應該渲染活動按鈕還是停用按鈕。 PS。 是的,我知道現在我發送選項會路由_savedGame
變量的副本。
菜單路線選項頁面按鈕。
RaisedButton(
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OptionsPage(_savedGame),
),
),
選項頁面
class OptionsPageState extends State<OptionsPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Options",
style: TextStyle(color: Colors.white),
),
backgroundColor: Colors.blueGrey[900],
),
body: Container(
alignment: Alignment.center,
color: Colors.cyan,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child:
Text('Delete saved games', style: TextStyle(fontSize: 40)),
onPressed:
widget.isGameSaved ? () => _showWarning(context) : null,
),
const SizedBox(height: 30),
RaisedButton(
child: Text('Back', style: TextStyle(fontSize: 40)),
onPressed: () {
Navigator.pop(context);
},
),
])),
),
);
}
Future<void> _showWarning(BuildContext context) {
return showDialog<void>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Are you sure you want to delete saved game?'),
actions: <Widget>[
FlatButton(
child: Text('No'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: Text('Yes'),
onPressed: () {
saveGame('empty');
Navigator.of(context).pop();
setState(() {
widget.isGameSaved = false;
});
},
),
],
);
},
);
}
}
如何為不同路徑中的變量“設置狀態”?
您可以做的是在導航器(如果使用的是導航器,則為MaterialApp)上方有一個InheritedWidget (稱GameStateWidget
)。 在InheritedWidget中有一個ValueNotifier,說出具有要共享的值的savedGame
。
然后在需要設置值的路線中
GameStateWidget.of(context).savedGame.value = ...
在您需要價值的路線中
ValueListenableBuilder(
valueListenable: GameStateWidget.of(context).savedGame,
builder: (context, savedGameValue, child) => ...
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.