简体   繁体   English

从 Flutter 中的 API 获取数据后如何导航到新屏幕?

[英]How to navigate to a new screen after data is fetched from API in Flutter?

In my main.dart file I have a Future that fetches data from an API ( json file).在我的main.dart文件中,我有一个从 API( json文件)获取数据的Future

What is the proper way that I can navigate to a new screen as soon as Future finishes fetching data?一旦Future完成获取数据,我可以导航到新屏幕的正确方法是什么?

You can do it like this:你可以这样做:

yourFutureObject.then((){
//write the code you want to run as soon as your Future finishes
  Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => 
  YourNewPage()));


});

I used some general names because you didn't post any code but you can write the function you want to run when Future finished and pass it to Future's then method我使用了一些通用名称,因为您没有发布任何代码,但是您可以编写 Future 完成时要运行的函数并将其传递给 Future 的 then 方法

So you have a Method that returns a Future所以你有一个返回未来的方法

bool asyncResult2 = await asyncFunc2();
if(asyncResult2)
{
Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondRoute()),
  );
}

asyncFunc2 funtion when completes the data fetching and assigning (or anything else) then all of these is done you can just pass the Future of boolean value true which states that every thing was done sucessfully and you can proceed to the second page or else if the the boolean value is false then there was something wrong with fetching or assigning asyncFunc2 函数在完成数据获取和分配(或其他任何事情)后,所有这些都完成了,您可以只传递布尔值 true 的 Future ,它表明每件事都已成功完成,您可以继续到第二页,否则布尔值是 false 那么获取或分配有问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM