Home > database >  Dart Future wait to complete before calling another Future
Dart Future wait to complete before calling another Future

Time:05-21

Looking for help here guys. I have 2 Futures that populate data in sqflite. I need one (_insertInitialData()) to finish first before calling the second one (_insertAdditionalData()). I have done it this way, but it's not working. It first does the re-recreation of the DB as expected, then both _insertInitialData() and _insertAdditionalData() not in the order I expected. I have tried .whenComplete and calling here _insertAdditionalData() and also have tried different ways that I think should work but nothing.

This is just something I'm doing for fun but still I'd like to know what I'm doing wrong.

TIA

Future<void> _insertAdditionalData() async{}

void populateDB() {
  try {
   final localDB = LocalDatabase.instance;
   Future.wait([localDB.dropDB(recreateDB: true)]).then((_){
    print('DB recreated!');
    Future.wait([_insertInitialData()]).then((_) {
     print('_insertInitialData done');
     Future.wait([_insertAdditionalData()]).then((_){
      print('_insertAdditionalData done');
     });
    });

   });
  } catch (ex) {
   print('There was a problem in populateDB(): $ex');
  }
 }```

CodePudding user response:

Using await makes things a lot easier to read and will block execution of later lines until the action has finished.

Future<void> populateDB() async {
  final localDB = LocalDatabase.instance;
  await localDB.dropDB(recreateDB: true);
  print('DB recreated!');
  await _insertInitialData();
  print('_insertInitialData done');
  await _insertAdditionalData();
  print('_insertAdditionalData done');
}

CodePudding user response:

You can try using only one future statement, and follows it with multiple "then". This makes sure the first "then" will be completed before the second "then" is executed. I assume your localDB.dropDB(recreateDB: true) function is asynchronous.

Future<void> _insertAdditionalData() async{}

void populateDB() {
  try {
    final localDB = LocalDatabase.instance;
    localDB.dropDB(recreateDB: true).then((_){
      print('DB recreated!');
    }).then((_) {
      _insertInitialData();
      print('_insertInitialData done');
    }).then(() {
      _insertAdditionalData();
      print('_insertAdditionalData done');
    });
  } catch (ex) {
    print('There was a problem in populateDB(): $ex');
  }
}

CodePudding user response:

Cool. Thanks for your comments. I replaced all of those Future.wait for async/await even in my internal methods that insert into the DB and it's all good!!! (executing in the sequence I need)

Just learning Dart/Flutter for fun and I love it.

  • Related