首页 > 解决方案 > sqflite-Flutter 数据库

问题描述

大家好,我是新手,一直在实习,我的老板让我学习 Flutter 中的数据库,我不知道我在做什么。谁能告诉我这是正确的做法还是错误的做法?

在我的数据库中将有 3 个表,Stock Item,Stock Category,Stock Group,

内部库存项目表将具有来自表库存类别和库存组的相关字段。

class ItemsDatabase {
  static final ItemsDatabase instance = ItemsDatabase._init();

  static Database? _database;

  ItemsDatabase._init();

  Future<Database> get database async {
    if (_database != null) return _database!;

    _database = await _initDB('items.db');
    return _database!;
  }

  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(path, version: 1, onCreate: _createDB);
  }

  Future _createDB(Database db, int version) async {
    final idType = 'INTEGER PRIMARY KEY AUTOINCREMENT';
    final textType = 'TEXT NOT NULL';
    final integerType = 'INTEGER NOT NULL';

    await db.execute('''
CREATE TABLE $tableItems ( 
  ${ItemFields.id} $idType, 
  ${ItemFields.description} $textType,
  ${ItemFields.cost} $integerType,
  ${ItemFields.price} $integerType,
  ${ItemFields.category} $textType,
  ${ItemFields.group} $textType
  )
''');
  }

  Future<Item> create(Item item) async {
    final db = await instance.database;

    final id = await db.insert(tableItems, item.toJson());
    return item.copy(id: id);
  }

  Future<Item> readNote(int id) async {
    final db = await instance.database;

    final maps = await db.query(
      tableItems,
      columns: ItemFields.values,
      where: '${ItemFields.id} = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return Item.fromJson(maps.first);
    } else {
      throw Exception('ID $id not found');
    }
  }

  Future<List<Item>> readAllItems() async {
    final db = await instance.database;

    final orderBy = '${ItemFields.id} ASC';
    // final result =
    //     await db.rawQuery('SELECT * FROM $tableNotes ORDER BY $orderBy');

    final result = await db.query(tableItems, orderBy: orderBy);

    return result.map((json) => Item.fromJson(json)).toList();
  }

  Future<int> update(Item item) async {
    final db = await instance.database;

    return db.update(
      tableItems,
      item.toJson(),
      where: '${ItemFields.id} = ?',
      whereArgs: [item.id],
    );
  }

  Future<int> delete(int id) async {
    final db = await instance.database;

    return await db.delete(
      tableItems,
      where: '${ItemFields.id} = ?',
      whereArgs: [id],
    );
  }

  Future close() async {
    final db = await instance.database;

    db.close();
  }
}

标签: databaseflutter

解决方案


我正在使用flutter插件objectdb 这个flutter插件为Dart和Flutter提供了持久的嵌入式面向文档的NoSQL数据库。100% 飞镖代码。浏览文档,实现很简单......我favorites_provider.dart的如下:

import 'dart:io';

import 'package:objectdb/objectdb.dart';
import 'package:objectdb/src/objectdb_storage_filesystem.dart';
import 'package:path_provider/path_provider.dart';

class FavoriteDB {
  var path ="";

  FavoriteDB(){getPath();}

  getPath() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    path = documentDirectory.path + '/favorites.db';
    print(path);
    //return path;
  }

  //Insertion
  add(Map item) async {
    final db = ObjectDB(FileSystemStorage(path));
    print(path);
    // db.open();
    db.insert(item);
    // db.tidy();
    await db.close();
  }

  Future<int> remove(Map item) async {
    final db = ObjectDB(FileSystemStorage(path));
    // db.open();
    int val = await db.remove(item);
    // db.tidy();
    await db.close();
    return val;
  }

  Future<List> listAll() async {
    final db = ObjectDB(FileSystemStorage(path));
    // db.open();
    List val = await db.find({});
    // db.tidy();
    await db.close();
    return val;
  }

  Future<List> check(Map item) async {
    final db = ObjectDB(FileSystemStorage(path));
    // db.open();
    List val = await db.find(item);
    // db.tidy();
    await db.close();
    return val;
  }
}

我正在使用MultiProvider它来实现它。

如何使用:

var favDB = FavoriteDB();


  checkFav() async {
    List c = await favDB.check({"id": entry.id});
    if (c.isNotEmpty) {
      setFaved(true);
    } else {
      setFaved(false);
    }
  }

  addFav() async {
    await favDB.add({"id": entry.id, "item": entry.toJson()});
    checkFav();
  }

  removeFav() async {
    favDB.remove({"id": entry.id}).then((v) {
      print(v);
      checkFav();
    });
  }

希望这对你有用。


推荐阅读