flutter,将数据保存到assets文件夹中的sqlite数据库

nc1teljy  于 2023-02-09  发布在  Flutter
关注(0)|答案(1)|浏览(292)

我创建了dogdb.db,插入了3行数据,将其保存在flutter项目的assets文件夹中,并注册到pubspec.yaml。然后,我运行以下代码,重新打开我的dogdb.db,我找不到新添加的数据。
1.如何将数据保存到assets文件夹中的dogdb.db?
1.我怎样才能确保资产文件夹中的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}';
       }
  }
55ooxyrt

55ooxyrt1#

assets文件夹是只读的,无法写入。在构建过程中,该文件夹被捆绑到一个存档中,Flutter应用可以在运行时读取该存档。
如果要保护应用程序的sqlite数据库,一种方法是使用sqflite_sqlcipher

相关问题