Home > Blockchain >  Flutter/Dart async/await not waiting
Flutter/Dart async/await not waiting

Time:06-21

I have this piece of code:


  List<String> allSlokamIdsList = [];
  List<Slokam> allSlokamsList = [];
  Map<String, List<String>> allSlokamsMap = {};
  List<String> sungSlokams = [];
  var knownSlokams = {'nma': <String>[], 'mpd': <String>[]};

  late String currentAksharam;
  late String currentVrtham;
  var currentPlayerNo = 0;
  late String currentSlokam;

  @override
  void initState() {
    // ignore: todo
    // TODO: implement initState
    super.initState();
    print('in sadas');
    getData();
    doSetup();
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }

  Future<void> getData() async {
    allSlokamsList = await dbHelper.getSlokams();
    allSlokamIdsList = await dbHelper.getSlokamIds();
    // print(allSlokamsList[1].first_line);
  }

  void doSetup() async {
    _init();
    _getAudioList();
    player.playbackEventStream.listen((event) {
      if (event.processingState == ProcessingState.completed) {
        slokamCompleted();
      }
    });
  }

  void _init() {
    print('_init');
    isPlaying = false;
    isPaused = false;
    isStopped = true;
    print('allSlokamsList = $allSlokamsList');

    for (var item in allSlokamsList) {
      allSlokamsMap[item.slokam_id] = [
        item.aksharam,
        item.aksharam3,
        item.slokam_text
      ];
    }
    print('allSlokamsMap=$allSlokamsMap');
  }


The await in the getdata() is not waiting for the operation to finish, apparently.

When the code in _init() is executed, the getdata() is not complete and as a result, the allSlokamsList is emplty.

The print statements are producing the following output:

I/flutter (17648): in sadas

I/flutter (17648): _init

I/flutter (17648): allSlokamsList = []

I/flutter (17648): allSlokamsMap={}

How can I fix this?

CodePudding user response:

it is because you called doSetUp function on initState. Call doSetUp in getData function.

Future<void> getData() async {
allSlokamsList = await dbHelper.getSlokams();
allSlokamIdsList = await dbHelper.getSlokamIds();
doSetUp();
}

CodePudding user response:

Problem is your getData function and doSetup were called synchronously. There are usually 2 ways that you can fix this.

  1. Use then:
getData().then((_)=>doSetup());
  1. Make a separated function, make sure it has async, the function's return value can be void or Future<void> based on your use case:
void init() async {
    await getData();
    doSetup();
}
  1. (Not recommended) You can have your doSetup called inside your getData
Future<void> getData() async {
    allSlokamsList = await dbHelper.getSlokams();
    allSlokamIdsList = await dbHelper.getSlokamIds();
    doSetup(); //Don't do this
}

It's not recommended because getData function should only for getting data, not doing any kind of setup.

  • Related