在Flutter数据库创建中,类型'Future <dynamic>'不是类型'Future <int>'的子类型

时间:2018-07-24 05:39:42

标签: dart flutter flutter-dependencies

我是Flutter应用程序开发的新手。在Flutter应用程序中,我使用路径提供程序插件和SQFLite创建数据库。但它不起作用,它显示异常消息 'Future'类型不是'Future'类型的子类型

我在这里添加代码

SET autocommit = 0 ;

--Insert/Update/Delete stuff here
COMMIT ; 

请帮助我。请给个建议。预先感谢。

 static final DatabaseHelper _instance = new DatabaseHelper.internal();
  factory DatabaseHelper() => _instance;

  static Database _db;

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  DatabaseHelper.internal();

  initDb() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, "tododatabase.db");
    var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return ourDb;
  }

  Future _onCreate(Database db, int version) async {
    await db.execute(
        "CREATE TABLE TodoList(id INTEGER PRIMARY KEY, todoText TEXT)");
    // print("Table is created");
  }

//insertion
  Future<int> saveTodo(Todo todo) async {
    var dbClient = await db;
    int res = await dbClient.insert(" TodoList", todo.toMap());
    return res;
  }

这是我得到的日志。

2 个答案:

答案 0 :(得分:0)

您需要具有一个Future,用于为initDB()方法返回类型数据库:

Future<Database> initDB() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, "event.db");
var theDatabase = await openDatabase(path, version: 1, onCreate: _onCreate);
return theDatabase;
}

一个完整的例子在这里:

https://github.com/dazza5000/austin-feeds-me-flutter/blob/master/lib/data/event_database.dart

class EventsDatabase {
  static const EVENT_TABLE_NAME = "event";
  static final EventsDatabase _instance = EventsDatabase._internal();

  factory EventsDatabase() => _instance;

  static Database _db;

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDB();
    return _db;
  }

  EventsDatabase._internal();

  Future<Database> initDB() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, "event.db");
    var theDatabase = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDatabase;
  }

  void _onCreate(Database db, int version) async {
    await db.execute("CREATE TABLE " + EVENT_TABLE_NAME + " ("
        "id STRING PRIMARY KEY, "
        "name TEXT, "
        "time INTEGER, "
        "description TEXT, "
        "url TEXT, "
        "photo TEXT, "
        "lat DOUBLE, "
        "lng DOUBLE)");
  }

  Future closeDb() async {
    var dbClient = await db;
    return dbClient.close();
  }
}

答案 1 :(得分:0)

您的onCreate()函数应为void类型(而不是Future),并且应为async