【问题标题】:Flutter: Where to place sqflite code inside my application?Flutter:在我的应用程序中放置 sqflite 代码的位置?
【发布时间】:2020-08-30 05:37:38
【问题描述】:

我想在我的应用程序中使用 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],
      );
    }
  }
}

【问题讨论】:

    标签: sqlite flutter dart sqflite


    【解决方案1】:

    不,无论您在哪里创建数据库都没有关系。

    您可以创建一个文件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 文件中创建类,并且希望将每个函数都保留为顶级函数,那么您可以执行以下操作。

    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 database = //yoir 代码,而是这样做,数据库 =//你的代码.. 通过这样做,你将初始化数据库变量,并作为数据库变量是一个全局变量(在任何函数外部、类内部声明),任何函数都可以访问它。但是您必须记住,必须在调用任何其他需要数据库的方法之前初始化数据库,因为如果您不会在任何其他函数之前调用任何 () 方法,那么数据库将不会被初始化,因此您的其他功能将无法使用。

    例子,

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

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

    【讨论】:

    • 所以我创建了文件 databaseServices.dart 并将我的代码放在那里。为此,我必须创建一个类和一个异步函数来将代码嵌套在其中。现在,如何在其他文件中调用插入、更新和删除方法?
    • 如果有帮助,请考虑投票并接受这个作为答案:)
    • 嗨,@Madhavam Shahi,你帮了很多忙!我刚刚更新了我的问题,你能告诉我我做错了什么吗?
    • 嗯,db.delete() 只是一个例子,对于删除,你有一个名为 deleteCounter() 的方法,当你想删除一个计数器时,你必须调用该方法并传递一个 id .希望对您有所帮助。
    • 我知道这是一个例子。问题是,在使用DataBaseServices db=DataBaseServices(); 创建对象后,我无法访问对象的方法。 Tje 唯一可用的方法是whatever(),我看不到其中的其他功能。我试图从 databaseServices.dart 中删除此方法,但删除它会导致各种错误。
    猜你喜欢
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2012-07-09
    • 2022-07-25
    • 2019-06-23
    相关资源
    最近更新 更多