Home > Net >  How to wait for a request to complete using ObservableFuture?
How to wait for a request to complete using ObservableFuture?

Time:09-17

When I transition to a screen where I get a list of information via an API, it initially gives an error:

_CastError (Null check operator used on a null value)

and only after loading the information, the screen is displayed correctly.

I am declaring the variables like this:

@observable
ObservableFuture<Model?>? myKeys;

@action
getKeys() {
  myKeys = repository.getKeys().asObservable();
}

How can I enter the page only after loading the information?

In button action I tried this but to no avail!

await Future.wait([controller.controller.getKeys()]);
Modular.to.pushNamed('/home');

I appreciate if anyone can help me handle ObservableFuture correctly!

CodePudding user response:

You need to call the "future" adding

Future.wait

(the return type of getKeys) keys=await Future.wait([
controller.getKeys();
]);

CodePudding user response:

The problem is your getKeys function isn't returning anything, so there's nothing for your code to await. You need to return a future in order to await it.

Future<Model?> getKeys() {
  myKeys = repository.getKeys().asObservable();
  return myKeys!; // Presumably this isn't null anymore by this point.
}

...

await controller.controller.getKeys();
Modular.to.pushNamed('/home');
  • Related