(Flutter/Dart) Two async methods in initState not working

女生的网名这么多〃 提交于 2019-12-11 15:08:49

问题


I have a function in my initState:

  @override
      void initState() {
       _fetchListItems();
        super.initState();
      }

This function is very simple. It has two async await operations of sqflite, one of which waits for the other to complete in it:

 _fetchListItems() async {
       wait() async {
         number = await db.getNumber(userId); }

       await wait();
     List rawFavouriteList = await db.getList(number);

      setState((){
      rawFavouriteList.forEach((item){
           _favouriteList.add(Model.map(item));
               }}); 
 }

I have to wait for number to be fetched, only then I can fetch serialized List, which then I deserialize and populate then add to the List which is displayed in ListView.

The problem is, this is not working in initState. It's working fine when it's called through onPressed() of a button, but not in initState.

Points to Note:

1) There is no error being thrown

2) I have already tried more conservative alternatives by using await for even rawFavouriteListthrough a separate function like wait() before using setState() top populate the _favouriteList, even though it's working fine manually through buttons.

3) Everything works fine if I manually enter number value in the second database query and just remove the first query, i.e.

_fetchListItems() async {
      List rawFavouriteList = await db.getList(42);
  setState((){
  rawFavouriteList.forEach((item){
       _favouriteList.add(Model.map(item));
           }}); 
  }

来源:https://stackoverflow.com/questions/56693883/flutter-dart-two-async-methods-in-initstate-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!