2

In my main.dart file I have a Future that fetches data from an API (json file).

What is the proper way that I can navigate to a new screen as soon as Future finishes fetching data?

kamranbekirovyz
  • 1,208
  • 1
  • 13
  • 33

2 Answers2

1

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

Morez
  • 2,085
  • 2
  • 10
  • 33
  • where this could be written? only place I can think of is inside `initState()` also in order to trigger the `Future` – kamranbekirovyz Apr 02 '20 at 18:28
  • You can write it in your build function because you have access to the BuildContext. Also because you’re using a Future object here, It would be possible to use it in initState(). Please refer to https://stackoverflow.com/questions/51965326/flutter-initstate-navigator-is-not-working for more – Morez Apr 02 '20 at 18:32
  • You can have a look at https://github.com/flutter/flutter/issues/19330 as well if you get any errors by using it in initState() but I think it would be fine to use it there – Morez Apr 02 '20 at 18:36
1

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

Sagar Acharya
  • 3,397
  • 4
  • 12
  • 34
  • the question is: where should I write this? `initState()` ? – kamranbekirovyz Apr 02 '20 at 18:26
  • 1
    If you want check at first glance then you can use the initstate. You can create a function and then call it in initstate method and then and just insert the code snippet that I have written – Sagar Acharya Apr 02 '20 at 18:39