Home > Mobile >  How to do this in Flutter ? Data Passing | Function call | Navigation
How to do this in Flutter ? Data Passing | Function call | Navigation

Time:06-01

Let's say that my code is currently inside a function in class X. In this function, I want to use Navigator.pushNamed to another class B and then after the result is populated i want to come back in class X and perform rest of the code.

e.g.,

Class X {
  function a() {
  --- Do something --
  // Go to class B and perform a specific operation - Don't move forward until class B is popped and we have the required result
  // Come back with the result of operation which we did in previous step
  -- Perform rest of the function calls using the result of operation --
  }
}

Is something like this possible using flutter ? Currently my code does route me to the other page (class B) but before class B is done populating the results, the rest of the code is already executed considering the calls are async.

Also, I'm not sure how i can send data back to class X from class B and only then move ahead with rest of the function

CodePudding user response:

Navigater has a .then method so you can do

Navigator.of(context).push(nextscreen).then((res)=>{
  // res will contain the data you passed back
  // Rest of your code here
});

and on the next screen

Navigator.pop(variable); // if you have data to pass back

CodePudding user response:

To execute code after widget 'ClassB' is popped,

  • Wait for the result from ClassB when it is popped

var result = await Navigator.push(...... //Here you push to B

  • Inside B, where you pop it, return a result

Navigator.pop(context, someResult)

  • make the function a, asynchronous

void a() async { .....

Because of the async-await keywords, your code (the lines after you push to ClassB) will be executed only after ClassB is popped

  • Related