我制作dogdb.db,插入3行数据,保存在flutter项目的assets文件夹中,注册到pubspec.yaml。然后,我运行以下代码并重新打开我的 dogdb.db 我找不到新添加的数据。
- 如何将数据保存到资产文件夹中的 dogdb.db?
如何保护资产文件夹中的 sqlite 数据库?
import 'dart:async'; import 'dart:io'; import 'package:flutter/services.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; void main() async { var databasesPath = await getDatabasesPath(); var path = join(databasesPath, "dog.db"); await deleteDatabase(path); ByteData data = await rootBundle.load(join("assets", "dogdb.db")); List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); await new File(path).writeAsBytes(bytes); final database = openDatabase( path ); Future<void> insertDog(Dog dog) async { final Database db = await database; await db.insert( 'dogs', dog.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); } Future<List<Dog>> dogs() async { final Database db = await database; final List<Map<String, dynamic>> maps = await db.query('dogs'); return List.generate(maps.length, (i) { return Dog( id: maps[i]['id'], name: maps[i]['name'], age: maps[i]['age'], ); }); } Future<void> updateDog(Dog dog) async { final db = await database; await db.update( 'dogs', dog.toMap(), where: "id = ?", whereArgs: [dog.id], ); } Future<void> deleteDog(int id) async { final db = await database; await db.delete( 'dogs', where: "id = ?", whereArgs: [id], ); } var fido = Dog( id: 0, name: 'Fido', age: 35, ); await insertDog(fido); print(await dogs()); fido = Dog( id: fido.id, name: fido.name, age: fido.age + 7, ); await updateDog(fido); print(await dogs()); await deleteDog(fido.id); print(await dogs()); var dido = Dog( id: 4, name: 'Dido', age: 10, ); await insertDog(dido); print(await dogs()); } class Dog { final int id; final String name; final int age; Dog({this.id, this.name, this.age}); Map<String, dynamic> toMap() { return { 'id': id, 'name': name, 'age': age, }; } @override String toString() { return 'Dog{id: $id, name: $name, age: $age}'; } }