top of page

[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 All

Comments


category

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page