【问题标题】:Flutter SQLlite the argument type 'Future<String>' can't be assigned to the parameter type 'String' errorFlutter SQLlite 参数类型“Future<String>”无法分配给参数类型“String”错误
【发布时间】:2020-10-22 01:31:01
【问题描述】:

我已经复制并修改了这个官方教程中的代码:https://flutter.dev/docs/cookbook/persistence/sqlite
我的插入版本如下所示:

final Future<Database> database = openDatabase(
    join(await getDatabasesPath(), 'user_database.db'),
    onCreate: (db, version) {
      return db.execute(
        "CREATE TABLE users(uid INTEGER PRIMARY KEY, display name TEXT, email TEXT)",
      );
    },
    version: 1,
  );
  Future<void> insertUser(User user) async {
  final Database db = await database;

  await db.insert(
    'users',
    user.toMap(),
    conflictAlgorithm: ConflictAlgorithm.replace,
  );

  final u = User("_displayName", "_email", "_ownerOfClub", "_password", "_id");

  await insertUser(u);

但它显示了 await getDatabasesPath() 部分的错误:对于 await 它说:意外的文本 'await',对于 getDatabasesPath():参数类型 'Future' 不能分配给参数类型'字符串'。

【问题讨论】:

    标签: sql database sqlite flutter


    【解决方案1】:

    试试这个方法

    
    Future<Database> database ;
    
    void openDBFunction() async {
    var databasesPath  = await getDatabasesPath();
    String path = join(databasesPath, 'demo.db');
    
    // open the database
        database = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
      // When creating the db, create the table
      await db.execute(
          'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
    });
    }
    
    

    void openDBFunction() async {
    
    // open the database
        database = await openDatabase(join(await getDatabasesPath(), 'demo.db'), version: 1,
        onCreate: (Database db, int version) async {
      // When creating the db, create the table
      await db.execute(
          'CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)');
    });
    }
    
    
    

    【讨论】:

    • 现在它为 getDatabasesPath() 的等待、openDatabase 和 openDataBase() 的第一个参数给出了一个错误,它表示只能在初始化程序中访问静态成员。
    • 你需要将它嵌套在一个异步函数中
    猜你喜欢
    • 2021-05-13
    • 2021-08-26
    • 2021-12-30
    • 2020-02-20
    • 1970-01-01
    • 2021-04-07
    • 2022-12-12
    • 1970-01-01
    • 2020-12-27
    相关资源
    最近更新 更多