Flutter:将 sqflite 代码放置在我的应用程序中的什么位置?

Flutter: Where to place sqflite code inside my application?

我想在我的应用程序中使用 sqflite。为此,我尝试按照本教程进行操作:https://flutter.dev/docs/cookbook/persistence/sqlite。但是,我不知道将代码放在我的应用程序中的什么位置。在教程中,代码似乎放在 main() 函数中 - 但是,如果我这样做,我如何才能在其他文件中调用插入、更新和删除方法?

更新:

按照@Madhavam Shahi 的建议,我创建了一个文件databaseServices.dart。现在,在另一个文件中,我正在导入 databaseServices.dart 并尝试按如下方式使用它:

import 'databaseServices.dart';
DataBaseServices db=DataBaseServices();
db.delete() //example

但是,它不起作用。我认为 databaseServices.dart 的结构不正确,但我无法发现错误。我知道我一定是犯了一个非常新手的错误。这是 databaseServices.dart:

的代码
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'counter.dart';

class DatabaseServices {
  
  void whatever() async {
    // Open the database and store the reference.
    final Future<Database> database = 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 Database db = await database;
      // 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 Database db = await database;
      // 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 database;
      await db.update(
        'counters',
        counter.toMap(),
        where: "id = ?",
        whereArgs: [counter.id],
      );
    }

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

不,创建数据库的位置无关紧要。

您可以创建一个文件 databaseServices.dart 来管理数据库服务。届时您可以轻松管理您的代码。

在食谱中,他们只是展示了一个示例,您可以如何使用 sqlflite

但是,如果您在 main() 方法中执行异步任务,那么您应该将此行 WidgetsFlutterBinding.ensureInitialized(); 放在您的 main() 方法中。

更新:

要在其他文件中执行CRUD,

  1. 导入您的 databaseServices.dart 文件,您要在其中执行 CRUD。
import 'databaseServices.dart';

DataBaseServices db=DataBaseServices();// create an object (DataBaseServices is the name of the class)

//Now, you can access all the methods,

db.delete()//example

或者,如果您不想在 databaseServices.dart 文件中创建 class,并且希望每个函数都保持为顶级函数,那么您可以执行以下操作。

import 'databaseServices.dart' as db;

//Now, you can access all the top level functions or variables.

db.delete()//example.

更新 2:-

要使每个函数都可以访问数据库,

  1. 将 Future 数据库移到 whatever () 方法之外,并将其放在 class 名称的正下方。 (使其成为全局的,以便每个函数都可以访问它),注意我删除了“final”关键字,因为我们稍后将在 whatever 方法中初始化它。现在,在任何方法中做你曾经做过的事情,但不是最终的 Future database = //yoir code,而是这样做,database =//your code ..通过这样做,你将初始化数据库变量,并作为数据库变量是一个全局变量(在任何函数外声明,在class内),任何函数都可以访问它。但是你必须记住,在调用任何其他需要数据库的方法之前必须初始化数据库,因为如果你不在任何其他函数之前调用任何 () 方法,那么数据库将不会被初始化,因此您的其他功能将无法使用。

示例,

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

class DatabaseServices {
  Future<Database> database;//making database global so that every function inside the class can access it.
  void whatever() async {
    // Open the database and store the reference.
    database = 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,
    );
}//Function whatever () ends here
    // Define a function that inserts counters into the database.
    Future<void> insertCounter(Counter counter) async {
      // Get a reference to the database.
      final Database db = await database;
      // 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 Database db = await database;
      // 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 database;
      await db.update(
        'counters',
        counter.toMap(),
        where: "id = ?",
        whereArgs: [counter.id],
      );
    }

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


现在,由于没有嵌套函数,您可以轻松创建 class 的对象,并根据需要轻松调用函数:)