1

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

我不喜欢的是,每次都必须评估数据库以确定是否需要像“数据库 db = await this.db;”那样创建它。如果它只是在创建类时创建,然后仅用作实例化,我会更喜欢它。但是,我不熟悉“._internal”,也不熟悉“工厂”,所以我不确定实现该目标的最佳方式。

如果有人能告诉我如何最好地实现这一目标,我将不胜感激。IE。不再需要“Database db = await this.db;”,只需引用 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;
  }
4

1 回答 1

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");
  }

主要.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()));
}
于 2019-03-22T09:34:52.740 回答