Is that Future<>s pattern possible to do in dart(Flutter) as it is in JS?

Issue

I need to do something like this using dart’s Futures(or else):

function Obj(){
  let resolver;

  this.promise = new Promise((resolve, reject) => {
    resolver = resolve;
  });


    //await firebase initialization or something
  setTimeout(() => {
      resolver('foo');
  }, 2000);
  
  return this;
}

var object = Obj();

(async () => {
  var result = await object.promise;
  console.log(result);
})();

Whats happening here, is I have an Object stored somewhere in a singleton(In JS example its an object<Obj> ) that is initialized somewhere at start, at the next line, there is another object initialized(In JS analogy its async() function). And this async function is waiting for object<Obj> to initialize its data like "foo" or else.

In JS, this setup is possible because Promises give you reference to resolveing function that you can use anywhere. But looking at Dart’s Futures I can’t find anything similar, which is odd.

TL;DR:

My goal is to have 1st object asyncronously initialize some data in its constructor and then somehow notify all other references to this object that data has been initialized.

Solution

  1. It is impossible to do that with Futures in dart as of now.

  2. But: I was overcomplicating, just use global state controller for that. Whenever data is received, state gets updated, updated state is easily tracked in other objects that reference that state(Using streams generally).

Answered By – Nick

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *