简体   繁体   中英

How to wait till function returns value flutter

I have a function which gets object from SQFlite db with id,

    var unit =  await getUnitById(1);

The function looks like this

Units getUnitById(int svrId) {
  db.initializeDatabase();
  Future<Units> unit = db.getUnitsBySvrId(1);
  unit.then((value) {
    print(value);
  });  
}

and the function in database helper (db) looks like this:

Future<Units> getUnitsBySvrId(int svrId) async {
if (svrId != null) {
  var unitsMapList = await getUnitMapListById(svrId);
  return Units.fromMapObject(unitsMapList[0]);
} else
  return null;
}

and query execution looks like this:

Future<List<Map<String, dynamic>>> getUnitMapListById(int id) async {
  Database db = await this.database;
  // var result = await db.rawQuery('SELECT * FROM $DOG_TABLE order by $ID ASC');
  var result =
    await db.rawQuery('SELECT * FROM $UNIT_TABLE WHERE $SERVER_ID = $id');
  return result;
}

I need to get Units object and use it, but when i call the function it waits and executes the code below and unit is null so my task is failed. i need to wait till i get data from db.

How can i achieve this??
I am so confused in using this async/ await.

try

Units getUnitById(int svrId) async {
db.initializeDatabase();
var unit =await db.getUnitsBySvrId(1);
return unit;
}

I hope it solve your issue

You can wrap the whole code like this,

Future<Units> getUnitById(int svrId) async {
    Completer<Units> completer = Completer();

    // If this line return future,like just below, we have to wait it too
    // await db.initializeDatabase(); 
    db.initializeDatabase();

    Units units = await db.getUnitsBySvrId(svrId);

    completer.complete(units);

    return completer.future;
}

Then call

var svrId = 1;
var units = await getUnitById(svrId);

This method could be written without Completer

Future<Units> getUnitById(int svrId) async {
    // If this line return future,like just below, we have to wait it too
    // await db.initializeDatabase(); 
    db.initializeDatabase();

    Units units = await db.getUnitsBySvrId(svrId);

    return units;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM