Flutter:创建类时如何最好地实例化SQFlite db对象

时间:2019-03-21 04:21:16

标签: flutter sqflite

我正在学习Flutter,目前正在学习第二个程序。该程序使用SQFlite,并且我从另一个似乎使用通用模式的程序中复制了大多数数据库处理。我对此做了一些修改。

我不喜欢的是,每次必须评估数据库以确定是否需要像“数据库db = await this.db;”中那样创建它。如果它是在创建类时简单创建的,然后将其用作实例化,则我更喜欢它。但是,我不熟悉“ ._internal”,也不熟悉“ factory”,因此我不确定实现该目标的最佳方法。

如果有人可以向我展示如何最好地实现这一目标,我将不胜感激。 IE浏览器无需使用“数据库db = await this.db;”,而只需引用该数据库。

DbHelper的相关代码的提取如下:

import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'noteRec.dart';

class DbHelper {
  static final DbHelper _dbHelper = DbHelper._internal();
  static const String sTblNotes = "Notes";
  static const String sColId = "Id";
  static const String sColTitle = "Title";
  static const String sColDetail = "Detail";

  DbHelper._internal();

  factory DbHelper() {
    return _dbHelper;
  }

  static Database _db;

  Future<Database> get db async {
    return _db != null ? _db : await initializeDb();
  }

  Future<Database> initializeDb() async {
    Directory dir = await getApplicationDocumentsDirectory();
    String path = dir.path + "/Notes.db";
    _db = await openDatabase(path, version: 1, onCreate: _createDb);
    return _db;
  }

  void _createDb(Database db, int newVersion) async {
    await db.execute(
        "CREATE TABLE $sTblNotes($sColId INTEGER PRIMARY KEY, $sColTitle TEXT, " +
            "$sColDetail TEXT)");
  }

  Future<List> getNoteRecs() async {
    Database db = await this.db;
    var result =
        await db.rawQuery("SELECT * FROM $sTblNotes ORDER BY $sColTitle ASC");
    return result;
  }

1 个答案:

答案 0 :(得分:0)

以下内容似乎可以满足我的要求。

dbHelper.dart

import 'dart:async';
import 'dart:io';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'noteRec.dart';

class DbHelper {
  static final DbHelper _dbHelper = DbHelper._internal();
  static const String sTblNotes = "Notes";
  static const String sColId = "id";
  static const String sColTitle = "title";
  static const String sColDetail = "detail";
  static Database _db;

  DbHelper._internal();

  factory DbHelper() {
    return _dbHelper;
  }

  Future<bool> openDb() async {
    if (_db == null) {
      Directory dir = await getApplicationDocumentsDirectory();
      _db = await openDatabase("${dir.path}/Notes.db",
          version: 1, onCreate: _createDb);
    }
    return (_db != null);
  }

  void _createDb(Database db, int newVersion) async {
    await db.execute(
        "CREATE TABLE $sTblNotes($sColId INTEGER PRIMARY KEY, $sColTitle TEXT, " +
            "$sColDetail TEXT)");
  }

  Future<List> getNoteRecs() async {
    return await _db
        .rawQuery("SELECT * FROM $sTblNotes ORDER BY $sColTitle ASC");
  }

main.dart

import 'package:flutter/material.dart';
import 'dbHelper.dart';
import 'NotesList.dart';

DbHelper _dbHelper = DbHelper();

void main() async {
  await _dbHelper.openDb();
  runApp(MaterialApp(home: NotesList()));
}