sqlite - Flutter:在我的应用程序中哪里放置 sqflite 代码?

标签 sqlite flutter dart sqflite

我想在我的应用程序中使用 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 .

但是,您应该放置此行 WidgetsFlutterBinding.ensureInitialized();在你的main()方法之前的任何事情,如果您正在 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 中创建类文件,并且希望将每个函数保留为顶级函数,那么您可以执行以下操作。

import 'databaseServices.dart' as db;

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

db.delete()//example.

更新2:-

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

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

示例,

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],
      );
    }
  }


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

关于sqlite - Flutter:在我的应用程序中哪里放置 sqflite 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63654317/

相关文章:

linux - 连接服务协议(protocol)时出错 : failed to connect to http://127. 0.0.1:41209/y-F2GYjV9_Y=/

flutter - 了解 api 调用和 jwt token barrer

dart - 使用Angular Dart使用WebSockets/服务器发送事件

android - 按查询分组在 ListView android 中显示一些意外结果

sqlite - 在 SQLite(或 Postgres)中,你能拥有一个行元素数量可变的表吗?

java - 一次插入数据库的多个表

android - 未找到 Android SDK。尝试设置 ANDROID_SDK_ROOT 环境变量

python - 使用 Python 检查然后更新 sqlite 中的行

dart - 即使展开时,Listview 中的 GridView 也会导致 "Vertical viewport was given unbounded height"

flutter - Gradle任务assembleDebug失败,退出代码为1,如何解决此问题?