Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected text 'await' when opening database with Flutter

I'm following the Persist data with SQLite tutorial from the Flutter Dev website, and I'm trying to open a database connection using async, but I keep getting the error Unexpected text 'await'. Even when I copy the code directly from the tutorial I'm still getting the same error.

This is my full file:

import 'dart:async';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

// Open the database and store the reference.
final Future<Database> database = openDatabase(
    join(await getDatabasesPath(), 'doggie_database.db'),
);

As far as I can tell I'm using the keyword correctly, so why is the compiler complaining?

I'm using Dart 2.7.0-dev.2.1 if that makes a difference.

like image 400
Andy Avatar asked Jan 24 '20 14:01

Andy


1 Answers

This seems like an issue with asynchronicity. It's strange that an example from the official documentation is leading you into this mistake. Directly assigning a variable outside of a method that would need to be async. Try this:

final Future<Database> database = getDatabasesPath().then((String path) {
  return openDatabase(join(path, 'doggie_database.db'));
});

For future reference, the reason why the OP's code wasn't working was because he was running it outside of the main() Flutter method, which is async in the example provided by the Flutter documentation: https://flutter.dev/docs/cookbook/persistence/sqlite#example

like image 126
João Soares Avatar answered Sep 22 '22 06:09

João Soares