[Flutter/Dart] Countermeasure when you want to perform asynchronous process in the constructor
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: init
Countermeasure
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: done
the 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.
Reference
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments