从单独的文件在main.dart中使用SQLite?

时间:2019-11-19 22:13:54

标签: sqlite flutter dart

我遵循了flutter文档中的这个简单示例。但是,这是写在单独的文件(db_test.db)中的。我的目标是在某个时候将数据转换为ListView。那么,我将如何使用CRUD操作,例如在main.dart中检索数据?我可以将其添加到main.dart文件中,但我希望保持其清洁和独立。

Official Flutter tutorial

我的db.dart文件

void main () async {
  final database = openDatabase(

    join(await getDatabasesPath(), 'to_do.db'),
    onCreate: (db, version) {
      return db.execute("CREATE TABLE tasks(id INTEGER PRIMARY KEY, title TEXT, created TEXT, INTEGER is_complete)");
    },
    version: 1,
  );

  Future<void> insertTask (Task task) async {
    final Database db = await database;

    await db.insert(
      'tasks',
      task.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace
    );
  }

  Future<List<Task>> tasks () async {
    final Database db = await database;

    final List<Map<String, dynamic>> maps = await db.query('tasks');

    return List.generate(maps.length, (i) {
      return Task(
        id: maps[i]['id'],
        title: maps[i]['title'],
        created: maps[i]['created'],
        isComplete: maps[i]['is_complete']
      );
    });
  }

  Future<void> updateTask(Task task) async {
    // Get a reference to the database.
    final db = await database;

    // Update the given Dog.
    await db.update(
      'tasks',
      task.toMap(),
      // Ensure that the Dog has a matching id.
      where: "id = ?",
      // Pass the Dog's id as a whereArg to prevent SQL injection.
      whereArgs: [task.id],
    );
  }

  Future<void> deleteTask(int id) async {
    // Get a reference to the database.
    final db = await database;

    // Remove the Dog from the database.
    await db.delete(
      'tasks',
      // Use a `where` clause to delete a specific dog.
      where: "id = ?",
      // Pass the Dog's id as a whereArg to prevent SQL injection.
      whereArgs: [id],
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用静态成员创建一个包含Class的新文件来提供帮助。静态成员可确保在整个应用程序中仅创建一个数据库实例。

class DatabaseHelper {
  static Database _database;

  ///Returns db instance if already opened
  ///else call the initDatabase
  static Future<Database> getDBConnector() async {
    if (_database != null) {
      return _database;
    }

    return await _initDatabase();
  }

  ///Open DB Connection, returns a Database instance.
  ///
  static Future<Database> _initDatabase() async {
    _database = await openDatabase(
      join(await getDatabasesPath(), "my_path.db"),

      onCreate: (db, version) async {
        //on create
      },
      version: 1,
    );

    return _database;
  }

  //put your CRUD in static function
  static Future<void> insertTask (Task task) async {
    final Database db = await getDBConnector();

    await db.insert(
      'tasks',
      task.toMap(),
      conflictAlgorithm: ConflictAlgorithm.replace
    );
  }

  //the same with edit, delete
}

然后在另一个文件(如main.dart)中,您可以这样称呼它:

import "./databaseHelper.dart";
void caller() async{
  //create task

  //insert
  await DatabaseHelper.insertTask(task);
}

确保调用方是异步的。