flutter 持久化存儲-----數據庫sqflite|8月更文挑戰

Flutter中持久化存儲數據有多種方案, 通常經常使用的有 shared_preferencessqfitejava

  • shared_preferences: 包含NSUserDefaults(在iOS上)和SharedPreferences(在Android上),爲簡單數據提供持久存儲。數據以異步方式持久保存到磁盤。git

  • sqflite: 是一款輕量級的關係型數據庫,相似SQLite. 支持iOS和Android。適用於存儲數據庫 , 表類型的數據.github

sqflite的使用

添加依賴:

做者所用版本爲1.1.3sql

dependencies:
  ...
  sqflite: ^1.1.3
複製代碼

爲了方便,外面建立一個DatabaseHelper來封裝一些數據庫的相關操做:

先貼一下代碼 ,而後咱們逐行分析:數據庫

/* * author: Created by 李卓原 on 2019/3/12. * email: zhuoyuan93@gmail.com * */

import 'dart:async';

import 'package:path/path.dart';
import 'package:sale_aggregator_app/models/video.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = new DatabaseHelper.internal();

  factory DatabaseHelper() => _instance;

  final String tableVideo = 'VideoTable';
  final String columnId = 'id';
  final String image = 'image';
  final String url = 'url';
  final String duration = 'duration';
  final String title = 'title';
  final String favoriteStatus = 'favorite_status';

  static Database _db;

  DatabaseHelper.internal();

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();

    return _db;
  }

  initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'flashgo.db');

    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }

  void _onCreate(Database db, int newVersion) async {
    await db.execute(
        'CREATE TABLE $tableVideo($columnId INTEGER PRIMARY KEY, $image TEXT, $url TEXT, $duration INTEGER, $title TEXT, $favoriteStatus TEXT)');
  }

  Future<int> insertVideo(Video video) async {
    var dbClient = await db;
    var result = await dbClient.insert(tableVideo, video.toJson());

    return result;
  }

  Future<List> selectVideos({int limit, int offset}) async {
    var dbClient = await db;
    var result = await dbClient.query(
      tableVideo,
      columns: [columnId, image, url, duration, title, favoriteStatus],
      limit: limit,
      offset: offset,
    );
    List<Video> videos = [];
    result.forEach((item) => videos.add(Video.fromSql(item)));
    return videos;
  }

  Future<int> getCount() async {
    var dbClient = await db;
    return Sqflite.firstIntValue(
        await dbClient.rawQuery('SELECT COUNT(*) FROM $tableVideo'));
  }

  Future<Video> getVideo(int id) async {
    var dbClient = await db;
    List<Map> result = await dbClient.query(tableVideo,
        columns: [columnId, image, url, duration, title, favoriteStatus],
        where: '$id = ?',
        whereArgs: [id]);

    if (result.length > 0) {
      return Video.fromSql(result.first);
    }

    return null;
  }

  Future<int> deleteNote(String images) async {
    var dbClient = await db;
    return await dbClient
        .delete(tableVideo, where: '$image = ?', whereArgs: [images]);
  }

  Future<int> updateNote(Video video) async {
    var dbClient = await db;
    return await dbClient.update(tableVideo, video.toJson(),
        where: "$columnId = ?", whereArgs: [video.id]);
  }

  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
}

複製代碼

能夠看到咱們在執行相關方法的時候都會先得到db, db會執行一個initDb方法,用於建立數據庫和表json

initDb() async {
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'flashgo.db');

    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }
  
  void _onCreate(Database db, int newVersion) async {
    await db.execute(
        'CREATE TABLE $tableVideo($columnId INTEGER PRIMARY KEY, $image TEXT, $url TEXT, $duration INTEGER, $title TEXT, $favoriteStatus TEXT)');
  }
複製代碼
  • getDatabasesPath() : 獲取默認數據庫位置(在Android上,它一般是data/data/<package_name>/databases,在iOS上,它是Documents目錄)
  • join(databasesPath, 'flashgo.db'): 至關於在上述方法獲取到的位置建立了一個名爲flashgo的數據庫.
  • openDatabase: 按指定路徑打開數據庫 , 路徑就是上面flash.db的路徑,version爲數據庫版本號,onCreate是建立表的方法

而後是我定義的一個實體類,看一下代碼:markdown

class Video {
  int id;
  String image;
  String url;
  int duration;

  String title;
  bool favoriteStatus;

  Video(
      {this.id,
      this.image,
      this.url,
      this.duration,
      this.title,
      this.favoriteStatus});

  Video.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    image = json['image'];
    url = json['url'];
    duration = json['duration'];
    title = json['title'];
    favoriteStatus = json['favorite_status'];
  }

  Video.fromSql(Map<String, dynamic> json) {
    id = json['id'];
    image = json['image'];
    url = json['url'];
    duration = json['duration'];
    title = json['title'];
    favoriteStatus = json['favorite_status'] == 'true';
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['image'] = this.image;
    data['url'] = this.url;
    data['duration'] = this.duration;
    data['title'] = this.title;
    data['favorite_status'] = this.favoriteStatus;
    return data;
  }
}

複製代碼

細心的同窗可能看到了一個不同凡響的方法: fromSql , 其中的json['favorite_status'] 是字符串類型, 爲何不依然用bool型呢, 由於sqlite不支持bool型.app

上文中,CREATE TABLE $tableVideo($columnId INTEGER PRIMARY KEY, $image TEXT, $url TEXT, $duration INTEGER, $title TEXT, $favoriteStatus TEXT) 這個建表方法能夠看到 id用的是integer, 其餘都是用的text.異步

咱們看一下sqlite都支持哪些數據類型吧:async


sql存儲數據類型

每一個存儲在 SQLite 數據庫中的值都具備如下存儲類之一:

存儲類 描述
NULL 值是一個 NULL 值。
INTEGER 值是一個帶符號的整數,根據值的大小存儲在 一、二、三、四、6 或 8 字節中。
REAL 值是一個浮點值,存儲爲 8 字節的 IEEE 浮點數字。
TEXT 值是一個文本字符串,使用數據庫編碼(UTF-八、UTF-16BE 或 UTF-16LE)存儲。
BLOB 值是一個 blob 數據,徹底根據它的輸入存儲。

數據庫和表已經準備就緒了,那麼該看一看它的增刪改查了

插入數據
Future<int> insertVideo(Video video) async {
    var dbClient = await db;
    var result = await dbClient.insert(tableVideo, video.toJson());

    return result;
  }
複製代碼

這裏是我封裝的一個插入數據的方法,參數是video的對象, 可是能夠看到insert方法第二個參數是一個json數據,因此其實也能夠直接傳遞json數據.而不是傳一個對象再轉成json.

查詢方法

Future<List> selectVideos({int limit, int offset}) async {
    var dbClient = await db;
    var result = await dbClient.query(
      tableVideo,
      columns: [columnId, image, url, duration, title, favoriteStatus],
      limit: limit,
      offset: offset,
    );
    List<Video> videos = [];
    result.forEach((item) => videos.add(Video.fromSql(item)));
    return videos;
  }
複製代碼

主要是調用了query方法,先看一下源碼:

Future<List<Map<String, dynamic>>> query(String table,
      {bool distinct,
      List<String> columns,
      String where,
      List<dynamic> whereArgs,
      String groupBy,
      String having,
      String orderBy,
      int limit,
      int offset});
複製代碼

有一個必傳參數是表名, 而後有不少修飾, 好比 limit : 是要查詢多少條數據, offset :是從哪裏開始查. columns: 是要查詢哪幾列 where: 是查詢條件,這裏我是查詢全部的因此沒有設置.

limit 和offset 這兩個也是最經常使用的屬性,因此我封裝方法的時候容許設置這兩個參數. 若是你有多張表,多個列須要查詢,我建議各自封裝方法,否則的話,須要傳入的參數過於複雜便失去了封裝的意義.

這裏的查詢方法返回的是json數據,且要記住,是隻有integer和text類型的,因此想要bool必定要本身處理

List<Video> videos = [];
    result.forEach((item) => videos.add(Video.fromSql(item)));
複製代碼

因此這裏,我新建了一個fromSql的方法,把查詢出來的json數據轉成我想要的類型的對象.

查詢單個
Future<Video> getVideo(int id) async {
    var dbClient = await db;
    List<Map> result = await dbClient.query(tableVideo,
        columns: [columnId, image, url, duration, title, favoriteStatus],
        where: '$id = ?',
        whereArgs: [id]);

    if (result.length > 0) {
      return Video.fromSql(result.first);
    }

    return null;
  }
複製代碼

思路同上,只是要多了一個where,即查詢條件,這裏我是根據id來查 因此只傳入了一個id參數. 返回查詢到的結果(json類型) . 若是查詢不到,則返回一個null.

更改數據

Future<int> updateVideo(Video video) async {
    var dbClient = await db;
    return await dbClient.update(tableVideo, video.toJson(),
        where: "$columnId = ?", whereArgs: [video.id]);
  }
複製代碼

這個代碼的邏輯是

  1. 傳入更改後的數據
  2. 根據傳入的數據id找到對應數據
  3. 更新數據

刪除數據

Future<int> deleteVideo(String images) async {
    var dbClient = await db;
    return await dbClient
        .delete(tableVideo, where: '$image = ?', whereArgs: [images]);
  }
複製代碼

其實邏輯和查詢是同樣的,我這是根據image來查找並刪除.也能夠用id或者其餘數據.

獲取數據的數量

Future<int> getCount() async {
    var dbClient = await db;
    return Sqflite.firstIntValue(
        await dbClient.rawQuery('SELECT COUNT(*) FROM $tableVideo'));
  }
複製代碼

此方法用來查詢表中有多少條數據. 這我用了rawQuery方法, 它是支持直接使用sql語句進行查詢的. 由於該結果返回一個列表,因此使用Sqflite.firstIntValue來獲取其中的第一個值.

關閉方法

Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
複製代碼

在操做執行完畢後 , 記得關閉數據庫.關閉以後沒法再訪問數據庫.

以上是對代碼的分析,下面看一下實際的使用:

//把視頻列表存到數據庫以備用
  void saveVideos(List<Video> videos) async {
    var db = DatabaseHelper();
    videos.forEach((v) => db.insertVideo(v));
    db.close();
  }
複製代碼

相關代碼盡在[github]flutter_study/sqflite_page.dart at master · lizhuoyuan/flutter_study (github.com))

相關文章
相關標籤/搜索