[Flutter/Dart] Countermeasure when you want to perform asynchronous process in the constructor
- M.R

- Jul 10, 2023
- 1 min read
Problem
There are times when you want to do asynchronous process in the constructor of a Dart class.
For example, the initial value is the value obtained from the remote database.
However, the syntax below will result in a compilation error.
class testClass{
testClass()async{
await _init();
}
//← The modifier 'async' can't be applied to the body of a constructor.
Future<void> _init()async{
await Future.delayed(const Duration(seconds: 1));
}
}It seems that the constructor should return a testClass, not a Future.
However the following compiles, but parent process does not wait for _init() to complete.
class testClass{
testClass(){
_init();
}
Future<void> _init()async{
await Future.delayed(const Duration(seconds: 1));
}
}That is,
class testClass{
testClass(){
_init();
debugPrint("construct");
}
Future<void> _init()async{
await Future.delayed(const Duration(seconds: 1));
debugPrint("init");
}
}
void main(){
testClass _test = testClass();
debugPrint("done");
}results in
flutter: construct
flutter: done
flutter: initCountermeasure
Create a static method that creates an instance.
class testClass{
testClass(){
}
static Future<testClass> create()async{
testClass _test = testClass();
await _test._init();
debugPrint("construct");
return _test;
}
Future<void> _init()async{
await Future.delayed(const Duration(seconds: 1));
debugPrint("init");
}
}If you do the following
void main()async{
testClass _test = await testClass.create();
debugPrint("done");
}flutter: init
flutter: construct
flutter: donethe order went as expected.
Lastly
There seems to be a lot of controversy regarding this topic, such as wanting to be able to use constructors instead of static methods, or that constructors shouldn't be awaited in the first place.






Comments