Xkfkxkmkodm28299
Xkfkxkmkodm28299

Reputation: 11

Best way to get value from future in constructor in dart

what ways you suggest for getting value from future in object constructor ?

class F{
late SomeObj<t> _obj;
F(){
 () async{
    _obj = await someFuture();
  }.call();
}
 somefunc() => doing something with _obj

}

but this doesn't gave me right res in the right time, Other ways for this situation?

Upvotes: 1

Views: 720

Answers (1)

jamesdlin
jamesdlin

Reputation: 89955

Here are two possible approaches:

  • Make your class's constructor private and force callers to instantiate your class via an asynchronous static method. From the perspective of callers, there is little difference between calling a static method and a named constructor.

    class F {
      late SomeObj<T> _obj;
    
      F._();
    
      static Future<F> create() async {
        var f = F._();
        f._obj = await someFuture();
        return f;
      }
    
      Object? someFunc() => doSomethingWith(_obj);
    }
    
  • Explicitly make everything that depends on the asynchronous value also asynchronous. If _obj is initialized asynchronously, then _obj should be a Future. If someFunc depends on _obj, then someFunc should return a Future.

    class F {
      Future<SomeObj<T>> _obj;
    
      F() : _obj = someFuture();
    
      Future<Object?> someFunc() async => doSomethingWith(await _obj);
    }
    

Upvotes: 1

Related Questions