Flutter:为什么此函数内的方法无法访问数据库变量?

问题描述

我有一个名为(async () => { const sub = await stripe.subscriptions.retrieve('sub_HurxwcQoCIH7jv') console.log(sub) // })() 文件。该文件具有使用各种方法的类。第一种方法打开数据库并存储引用,而其他方法对该数据库进行包含,更新和删除。问题在于其他方法无法看到第一种方法创建的数据库。我想念什么?

代码如下:

const functionWithSomeName = async () => {
  const sub = await ...CODE HERE...
  console.log(sub)
}

functionWithSomeName()

解决方法

database变量仅存储在initDatabase方法中,而不存储在DatabaseServices类中,这意味着只能从initDatabase方法进行访问。 / p>

下面的代码示例显示如何将database作为属性存储在DatabaseServices类上,以允许该类内的所有方法使用它。

class DatabaseServices {
  Future<Database> _db;

  Future<void> initDatabase() async {
    // Open the database and store the reference.
    _db = openDatabase(
      // Set the path to the database.
      join(await getDatabasesPath(),'counter_database.db'),// When the database is first created,create a table to store counters;
      onCreate: (db,version) {
        // Run the CREATE TABLE statement on the database.
        return db.execute(
          "CREATE TABLE counters(id INTEGER PRIMARY KEY,name TEXT,value INTEGER)",);
      },// Set the version. This executes the onCreate function and provides a
      // path to perform database upgrades and downgrades.
      version: 1,);
  }

  // Define a function that inserts counters into the database.
  Future<void> insertCounter(Counter counter) async {
    // Get a reference to the database.
    final db = await _db;
    // Insert the Counter into the correct table. Here,if a counter is inserted twice,// it replace any previous data.
    await db.insert(
      'counters',counter.toMap(),conflictAlgorithm: ConflictAlgorithm.replace,);
  }

  // A method that retrieves all the counters from the counters table.
  Future<List<Counter>> counters() async {
    // Get a reference to the database.
    final db = await _db;
    // Query the table for all the Counters.
    final List<Map<String,dynamic>> maps = await db.query('counters');
    // Counvert the List<Map<String,dynamic>> into a List<Counter>
    return List.generate(maps.length,(i) {
      return Counter(
        id: maps[i]['id'],name: maps[i]['name'],value: maps[i]['value'],);
    });
  }

  // Method to update a Counter in the database
  Future<void> updateCounter(Counter counter) async {
    final db = await _db;
    await db.update(
      'counters',where: "id = ?",whereArgs: [counter.id],);
  }

  //Delete a Counter from the database
  Future<void> deleteCounter(int id) async {
    final db = await _db;
    await db.delete(
      'counters',whereArgs: [id],);
  }
}

您可以找到有关打开数据库here的更多信息。