Flutter中數(shù)據(jù)庫的使用教程詳解
在Flutter開發(fā)過程中,我門有時(shí)候需要對(duì)一些數(shù)據(jù)進(jìn)行本地的持久化存儲(chǔ),使用sp文件形式雖然也能解決問題,但是有時(shí)數(shù)據(jù)量較大的時(shí)候,顯然我們文件形式就不太合適了,這時(shí)候我們就需要使用數(shù)據(jù)庫進(jìn)行存儲(chǔ),我們知道在原生中有系統(tǒng)提供的輕量級(jí)sqlite數(shù)據(jù)庫,在Flutter強(qiáng)大的生態(tài)環(huán)境中,也有這樣一個(gè)數(shù)據(jù)庫插件sqflite: ^2.0.2可以同時(shí)在Androud、iOS中進(jìn)行數(shù)據(jù)庫操作。
1、 創(chuàng)建數(shù)據(jù)庫:這里我以存儲(chǔ)我的搜索歷史記錄為例。
首先導(dǎo)入:
import 'package:sqflite/sqflite.dart';
這里我創(chuàng)建了一個(gè)數(shù)據(jù)庫幫助類,為了以后數(shù)據(jù)庫更新、升級(jí)等作準(zhǔn)備:
代碼實(shí)現(xiàn):主要是對(duì)Database這個(gè)類的獲取進(jìn)行了封裝。
/// 數(shù)據(jù)庫幫助類
class DbHelper {
final String path = "laoli.db"; // 數(shù)據(jù)庫名稱 一般不變
//數(shù)據(jù)庫中的表名字 這里是我存錯(cuò)歷史搜索記錄的表
static final searchTab = "SearchHistory";
//私有構(gòu)造
DbHelper._();
static DbHelper? _instance;
static DbHelper get instance => _getInstance();
factory DbHelper() {
return instance;
}
static DbHelper _getInstance() {
if (_instance == null) {
_instance = DbHelper._();
}
return _instance ?? DbHelper._();
}
/// 數(shù)據(jù)庫默認(rèn)存儲(chǔ)的路徑
/// SQLite 數(shù)據(jù)庫是文件系統(tǒng)中由路徑標(biāo)識(shí)的文件。如果是relative,
/// 這個(gè)路徑是相對(duì)于 獲取的路徑getDatabasesPath(),
/// Android默認(rèn)的數(shù)據(jù)庫目錄,
/// iOS/MacOS的documents目錄。
Future<Database>? _db;
Future<Database>? getDb() {
_db ??= _initDb();
return _db;
}
// Guaranteed to be called only once.保證只調(diào)用一次
Future<Database> _initDb() async {
// 這里是我們真正創(chuàng)建數(shù)據(jù)庫的地方 vserion代表數(shù)據(jù)庫的版本,如果版本改變
//,則db會(huì)調(diào)用onUpgrade方法進(jìn)行更新操作
final db =
await openDatabase(this.path, version: 1, onCreate: (db, version) {
// 數(shù)據(jù)庫創(chuàng)建完成
// 創(chuàng)建表 一個(gè)自增id 一個(gè)text
db.execute("create table $searchTab (id integer primary key autoincrement, name text not null)");
}, onUpgrade: (db, oldV, newV) {
// 升級(jí)數(shù)據(jù)庫調(diào)用
/// db 數(shù)據(jù)庫
/// oldV 舊版本號(hào)
// newV 新版本號(hào)
// 升級(jí)完成就不會(huì)在調(diào)用這個(gè)方法了
});
return db;
}
// 關(guān)閉數(shù)據(jù)庫
close() async {
await _db?.then((value) => value.close());
}
}在java后臺(tái)開發(fā)過程中,數(shù)據(jù)庫肯定都會(huì)分層設(shè)計(jì),這樣的好處可以在使用的過程中極大的提高代碼的健壯性以及降低后期的維護(hù)成本,在移動(dòng)前端雖然我們用數(shù)據(jù)庫的地方跟后臺(tái)相比少之又少,但是我還是建議也對(duì)數(shù)據(jù)庫進(jìn)行分層處理操作,雖然不分層也能實(shí)現(xiàn),但是這樣也可以降低我們的對(duì)于代碼的維護(hù)成本以及良好的編程習(xí)慣。廢話不多說,接下來我們需要?jiǎng)?chuàng)建處理數(shù)據(jù)的dao層。
這里sqflite封裝了一些常用的sql語法,比如增刪改查,我們就不需要自己去寫sql語法了,這里我簡(jiǎn)答封裝了下增刪改查的方法。
具體代碼:
/// 數(shù)據(jù)操作類
class DbSearchHistoryDao {
/// 增
static insert(String text) {
// 去重
queryAll().then((value) {
bool isAdd = true;
for (var data in value) {
if (data.name == text) {
isAdd = false;
break;
}
}
if (isAdd) {
DbHelper.instance.getDb()?.then((value) => value.insert(
DbHelper.searchTab,
DbSearchHotBean(name: text).toJson(),
));
}
});
}
/// 刪 全部
static deleteAll() {
DbHelper.instance.getDb()?.then((value) => value.delete(
DbHelper.searchTab,
));
}
/// 更新數(shù)據(jù) 通過id更新表內(nèi)具體行的數(shù)據(jù)
static update(DbSearchHotBean dbSearchHotBean) {
DbHelper.instance.getDb()?.then((value) => value.update(
DbHelper.searchTab,
dbSearchHotBean.toJson(),//具體更新的數(shù)據(jù)
where: "id = ?"http://通過id查找需要更新的數(shù)據(jù)
,whereArgs: [dbSearchHotBean.id]
));
}
/// 通過name查具體的實(shí)體類
static Future<DbSearchHotBean?> getBean(String name) async {
var db = await DbHelper.instance.getDb();
var maps = await db?.query(DbHelper.searchTab,
columns: ['id','name'],// 獲取實(shí)體類的哪些字段 默認(rèn)全部
where: 'name = ?',//通過實(shí)體類中的name字段
whereArgs: [name]);//具體name的值 限定數(shù)據(jù)
if(maps!=null && maps.length > 0) {
return DbSearchHotBean.fromJson(maps.first);
}
return null;
}
/// 查 全部all
static Future<List<DbSearchHotBean>> queryAll() async {
List<DbSearchHotBean> list = [];
await DbHelper.instance
.getDb()
?.then((db) => db.query(DbHelper.searchTab).then((value) {
for (var data in value) {
list.add(DbSearchHotBean.fromJson(data));
}
}));
return list;
}
}實(shí)體類:雖然只有一個(gè)字段,但是創(chuàng)建實(shí)體類方便以后擴(kuò)展。
class DbSearchHotBean {
int? id;
String? name; // 搜索詞
DbSearchHotBean({this.id,required this.name});
DbSearchHotBean.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
}
Map<String, String?> toJson() {
var map = <String, String?>{};
map['id'] = id?.toString() ;
map['name'] = name ?? "";
return map;
}
}具體用法就非常簡(jiǎn)單了:
增:DbSearchHistoryDao.insert(”搜索詞“);
刪全部:DbSearchHistoryDao.deleteAll();
改:例如將水改為火, 找到水的實(shí)體通過自增id修改name
DbSearchHistoryDao.getBean("水").then((value){
if(value!=null){
DbSearchHistoryDao.update(DbSearchHotBean(id: value.id,name: "火"));
}
});查全部:await DbSearchHistoryDao.queryAll();
到這里數(shù)據(jù)庫的基本用法就介紹完了,當(dāng)然部分操作比如刪指定數(shù)據(jù),批量修改、批量刪除等操作可以用 到批處理操作,這里就不過多介紹了,有需要的可以查看作者文檔。鏈接
batch = db.batch();
batch.insert('Test', {'name': 'item'});
batch.update('Test', {'name': 'new_item'}, where: 'name = ?', whereArgs: ['item']);
batch.delete('Test', where: 'name = ?', whereArgs: ['item']);
results = await batch.commit();總結(jié)
數(shù)據(jù)庫操作總體上沒什么難度,但是當(dāng)我們數(shù)據(jù)量比較多的時(shí)候,數(shù)據(jù)表結(jié)構(gòu)的設(shè)計(jì)就有一定的技術(shù)含量了,還有就是我們對(duì)于一些sql語句的掌握,因?yàn)榇瞬寮臀覀兎庋b了常用的功能,如果有比較特殊的需求,還是需要我們掌握一定的sql語法才行,這里就簡(jiǎn)單的介紹一些常用的方法,在移動(dòng)前端估計(jì)也基本夠用了~
到此這篇關(guān)于Flutter中數(shù)據(jù)庫的使用教程詳解的文章就介紹到這了,更多相關(guān)Flutter數(shù)據(jù)庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android 自定義縮短Toast顯示時(shí)間的實(shí)例代碼
這篇文章主要介紹了Android 自定義縮短Toast顯示時(shí)間,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01
Android FlowLayout流式布局實(shí)現(xiàn)詳解
這篇文章主要為大家詳細(xì)介紹了Android FlowLayout流式布局的實(shí)現(xiàn)方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09
Android 標(biāo)準(zhǔn)Intent的使用詳解
這篇文章主要介紹了Android 標(biāo)準(zhǔn)Intent的使用詳解的相關(guān)資料,需要的朋友可以參考下2017-03-03
Android實(shí)現(xiàn)微信朋友圈評(píng)論EditText效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)微信朋友圈評(píng)論EditText效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11
Android應(yīng)用中仿今日頭條App制作ViewPager指示器
這篇文章主要介紹了Android應(yīng)用中仿今日頭條App制作ViewPager指示器的例子,一般就是導(dǎo)航條在翻頁時(shí)的動(dòng)態(tài)字體變色效果,需要的朋友可以參考下2016-04-04
Android編程心得分享——JSON學(xué)習(xí)過程
在我們初步學(xué)習(xí)JSON時(shí)我們都知道JSON作為現(xiàn)在比較流行的數(shù)據(jù)交換格式,有著它的許多優(yōu)點(diǎn),這里將我學(xué)習(xí)JSON的過程記錄如下2013-06-06
Android日期和時(shí)間選擇器實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了Android日期和時(shí)間選擇器實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11

