我正在構建一個應用程式,我試圖通過呼叫 navigator.push 檢索資料
onTap: () async {
widget.dogData = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddDogScreen(),
),
);
widget.setDocId(widget.dogData['docId']);
setState(() {
widget.dogData;
});
},
但是,我想在 AddDogScreen 之后鏈接到另一個螢屏,并通過從該螢屏彈出來傳遞資料。
所以我們會有:
初始螢屏 -> AddDogScreen -> 另一個螢屏(然后彈出帶有資料的初始螢屏)
然后第三個螢屏應該會彈出資料的初始螢屏。由于我想從兩個螢屏獲取資料,我該如何設定?
提前非常感謝。
uj5u.com熱心網友回復:
為了做你想做的事,Flutter 導航中有兩個有用的功能:
final value = await Navigator.push()回傳推送的螢屏回傳的值,您可以等待它等待下一個螢屏的回傳。Navigator.pop(value)允許您在回傳時從螢屏回傳值。
您在這里所要做的就是與那些做您想做的事的人一起玩。這是您想要的流型別的示例:
class InitialScreen extends StatelessWidget {
onPressed(BuildContext context) async {
final List<String>? addDogScreenResult = await Navigator.of(context).push<
List<String>>(
MaterialPageRoute<List<String>>(builder: (context) => AddDogScreen()));
// Do something with the result
print("We got the values: ${addDogScreenResult}");
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => onPressed(context),
child: const Text("Click to go to AddDogScreen"))));
}
}
class AddDogScreen extends StatelessWidget {
onPressed(BuildContext context) async {
final String? anotherScreenResult = await Navigator.of(context)
.push<String>(MaterialPageRoute(builder: (context) => AnotherScreen()));
if (anotherScreenResult != null) {
const addDogScreenString = "Some value AddDogScreen generates";
// We can combine a value that we got in this screen and the return value of AnotherScreen.
final List<String> addDogScreenReturnValue = [
addDogScreenString,
anotherScreenResult
];
// We simply return the list using .pop() function
// Notice that we can type the .pop() function with the return type that we give it. It is not absolutely necessary, but it adds in clarity and safety.
Navigator.of(context).pop<List<String>>(addDogScreenReturnValue);
return;
}
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => onPressed(context),
child: const Text("Click to go to AnotherScreen"))));
}
}
class AnotherScreen extends StatelessWidget {
onPressed(BuildContext context) async {
const String anotherScreenResult = "Some value";
Navigator.of(context).pop<String>(anotherScreenResult);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => onPressed(context),
child: const Text("Click to go back to initial page"))));
}
}
另外,我在您的代碼中看到了widget.dogData = ...。也許這是故意的,但如果不是,這不是你應該操縱狀態的方式。狀態變數應該在擴展 StatefulWidget 的類中定義,并且您應該能夠使用 讀取它dogData,并使用以下方法更新它:
setState({
dogData = 'Something';
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412703.html
標籤:
