1

Can anyone help me how async and await work? The program complains that db is null when calling rawQuery(...). What I understood is the next statements after await won't be executed when function with await is not done yet, but the statements after an async functions won't wait for that function to finish its job. For example:

var db;

Widget build(BuildContext context) {
    ...
    List<Map<String, Object>> resultSet;
    asyncFunction();
    db.rawQuery(...).then((value) => resultSet = value);
    return Scaffold(
        appBar: AppBar(...),
        child: Text()
    );
     
}

void asyncFunction() async {
    String dbPath = await getDatabasesPath();
    String path = join(dbPath, 'sample.db');
    db = await openDatabase(path);
}

db is null in db.rawQuery(...). (I hope you get my point). I don't know if it is possible to put return Scaffold() inside then(...) or is it possible for Widget build() {...} to wait till all data are ready.

1 Answers1

0

EDIT : Sorry, I didn't noticed that you were in the build method of a widget.

Firstly, if you call your database here, you'll call your database EVERY TIME your widget re-build. That's not a good practice. You need to instanciate your database somewhere else (in a service for example). Once your data is load you can call it here.

Secondly, if you want to show data from a Future. You need to use a FutureBuilder, as @jamesdlin said.

rigorousCode
  • 385
  • 1
  • 2
  • 9
  • having an `async` in `build()` the compilers tells me that the `build()` function should return a `Future` – Naruto Uzumaki Apr 04 '21 at 21:04
  • [Use a `FutureBuilder`](https://stackoverflow.com/q/63017280/). BTW, `asyncFunction` should return a `Future` for callers to properly `await` it. – jamesdlin Apr 04 '21 at 21:06
  • @NarutoUzumaki I have update my answer, you can process like that. By the way, if you know the type of your db var, you can replace 'dynamic' by the right type :) – rigorousCode Apr 04 '21 at 21:09