Android?Flutter使用本地?cái)?shù)據(jù)庫編寫備忘錄應(yīng)用
前言
前面一篇我們介紹了使用 shared_preferences實(shí)現(xiàn)簡單的鍵值對(duì)存儲(chǔ),然而我們還會(huì)面臨更為復(fù)雜的本地存儲(chǔ)。比如資訊類 App會(huì)緩存一部分上次加載的內(nèi)容,在沒有網(wǎng)絡(luò)的情況下也能夠提供內(nèi)容;比如微信的聊天記錄都是存儲(chǔ)在手機(jī)客戶端。當(dāng)我們需要在本地存儲(chǔ)大量結(jié)構(gòu)化的數(shù)據(jù)的時(shí)候,使用 shared_preferences 顯然是不夠的。這個(gè)時(shí)候我們就需要使用本地?cái)?shù)據(jù)庫,移動(dòng)端最為常用的本地?cái)?shù)據(jù)庫是 SQLite。在 Flutter中同樣提供了對(duì) SQLite 的支持,我們可以使用 sqflite 這個(gè)插件搞定結(jié)構(gòu)化數(shù)據(jù)的本地存儲(chǔ)。本篇我們以一個(gè)完整的備忘錄的實(shí)例來講述如何使用 sqflite。
業(yè)務(wù)需求解讀
我們先來看備忘錄的功能:
- 顯示已經(jīng)記錄的備忘錄列表,按更新時(shí)間倒序排序;
- 按標(biāo)題或內(nèi)容搜索備忘錄;
- 添加備忘錄,并保存在本地;
- 編輯備忘錄,成功后更新原有備忘錄;
- 刪除備忘錄;
- 備忘錄通常包括標(biāo)題、內(nèi)容、創(chuàng)建時(shí)間和更新時(shí)間這些屬性。
可以看到,這其實(shí)是一個(gè)典型的數(shù)據(jù)表的 CRUD 操作。
實(shí)體類設(shè)計(jì)
我們設(shè)計(jì)一個(gè) Memo類,包括了 id、標(biāo)題、內(nèi)容、創(chuàng)建時(shí)間和更新時(shí)間5個(gè)屬性,用來代表一個(gè)備忘錄。同時(shí)提供了兩個(gè)方法,以便和數(shù)據(jù)庫操作層面對(duì)接。代碼如下:
import 'package:flutter/material.dart';
class Memo {
late int id;
late String title;
late String content;
late DateTime createdTime;
late DateTime modifiedTime;
Memo({
required this.id,
required this.title,
required this.content,
required this.createdTime,
required this.modifiedTime,
});
Map<String, dynamic> toMap() {
var createdTimestamp = createdTime.millisecondsSinceEpoch ~/ 1000;
var modifiedTimestamp = modifiedTime.millisecondsSinceEpoch ~/ 1000;
return {
'id': id,
'title': title,
'content': content,
'created_time': createdTimestamp,
'modified_time': modifiedTimestamp
};
}
factory Memo.fromMap(Map<String, dynamic> map) {
var createdTimestamp = map['created_time'] as int;
var modifiedTimestamp = map['modified_time'] as int;
return Memo(
id: map['id'] as int,
title: map['title'] as String,
content: map['content'] as String,
createdTime: DateTime.fromMillisecondsSinceEpoch(createdTimestamp * 1000),
modifiedTime:
DateTime.fromMillisecondsSinceEpoch(modifiedTimestamp * 1000),
);
}
}這里說一下,因?yàn)?SQLite 的時(shí)間戳(為1970-01-01以來的秒數(shù))只能以整數(shù)存儲(chǔ),因此我們需要在入庫操作(toMap)時(shí) DateTime 轉(zhuǎn)換為整數(shù)時(shí)間戳,在 出庫時(shí)(fromMap)將時(shí)間戳轉(zhuǎn)換為 DateTime。
數(shù)據(jù)庫工具類
我們寫一個(gè)基礎(chǔ)的數(shù)據(jù)庫工具類,主要是初始化數(shù)據(jù)庫和創(chuàng)建數(shù)據(jù)表,代碼如下:
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._init();
static Database? _database;
DatabaseHelper._init();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDB('database.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<void> _createDB(Database db, int version) async {
await db.execute('''
CREATE TABLE memo (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT,
created_time INTEGER,
modified_time INTEGER
)
''');
}
}創(chuàng)建數(shù)據(jù)表的語法和 MySQL 基本上是一樣的,需要注意的是字段類型沒有 MySQL 豐富,只支持簡單的整數(shù)(INTEGER)、浮點(diǎn)數(shù)(REAL)、文本(TEXT)、BLOB(二進(jìn)制格式,如存儲(chǔ)文件)。
備忘錄數(shù)據(jù)表訪問接口
我們?yōu)閭渫浱峁┮粋€(gè)數(shù)據(jù)庫的通用的訪問接口,包括了插入、更新、刪除和讀取備忘錄的方法。
import 'database_helper.dart';
import 'memo.dart';
Future<int> insertMemo(Map<String, dynamic> memoMap) async {
final db = await DatabaseHelper.instance.database;
return await db.insert('memo', memoMap);
}
Future<int> updateMemo(Memo memo) async {
final db = await DatabaseHelper.instance.database;
return await db
.update('memo', memo.toMap(), where: 'id = ?', whereArgs: [memo.id]);
}
Future<int> deleteMemo(int id) async {
final db = await DatabaseHelper.instance.database;
return await db.delete('memo', where: 'id = ?', whereArgs: [id]);
}
Future<List<Memo>> getMemos({String? searchKey}) async {
var where = searchKey != null ? 'title LIKE ? OR content LIKE ?' : null;
var whereArgs = searchKey != null ? ['%$searchKey%', '%$searchKey%'] : null;
final db = await DatabaseHelper.instance.database;
final List<Map<String, dynamic>> maps = await db.query(
'memo',
orderBy: 'modified_time DESC',
where: where,
whereArgs: whereArgs,
);
return List.generate(maps.length, (i) {
return Memo.fromMap(maps[i]);
});
}這里說明一下,sqflite 提供了如下方法來支持?jǐn)?shù)據(jù)庫操作:
insert:向指定數(shù)據(jù)表插入數(shù)據(jù),需要提供表名和對(duì)應(yīng)的數(shù)據(jù),其中數(shù)據(jù)為Map類型,鍵名為數(shù)據(jù)表的字段名。成功后會(huì)返回插入數(shù)據(jù)的id。update:按where條件更新數(shù)據(jù)表數(shù)據(jù),where條件分為兩個(gè)參數(shù),一個(gè)是where表達(dá)式,其中變量使用?替代,另一個(gè)是whereArgs參數(shù)列表,多個(gè)參數(shù)使用數(shù)據(jù)傳遞,用于替換表達(dá)式的?通配符。where條件支持如等于、大于小于、大于等于、小于等于、NOT、AND、OR、LIKE、BETWEEN 等,具體大家可以去搜一下。delete:刪除where條件指定的數(shù)據(jù),不可恢復(fù)。query:查詢,按指定條件查詢數(shù)據(jù),支持按字段使用orderBy屬性進(jìn)行排序。這里我們使用了LIKE來搜索匹配的標(biāo)題或內(nèi)容。
UI 界面實(shí)現(xiàn)
UI 界面比較簡單,我們看列表和添加頁面的代碼(編輯頁面基本和添加頁面相同)。備忘錄列表代碼如下:
class MemoListScreen extends StatefulWidget {
const MemoListScreen({Key? key}) : super(key: key);
@override
MemoListScreenState createState() => MemoListScreenState();
}
class MemoListScreenState extends State<MemoListScreen> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
List<Memo> _memoList = [];
@override
void initState() {
super.initState();
_refreshMemoList();
}
void _refreshMemoList({String? searchKey}) async {
List<Memo> memoList = await getMemos(searchKey: searchKey);
setState(() {
_memoList = memoList;
});
}
void _deleteMemo(Memo memo) async {
final confirmed = await _showDeleteConfirmationDialog(memo);
if (confirmed != null && confirmed) {
await deleteMemo(memo.id);
_refreshMemoList();
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('已刪除 "${memo.title}"'),
duration: const Duration(seconds: 2),
));
}
}
Future<bool?> _showDeleteConfirmationDialog(Memo memo) async {
return showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('刪除備忘錄'),
content: Text('確定要?jiǎng)h除 "${memo.title}"這條備忘錄嗎?'),
actions: [
TextButton(
child: const Text(
'取消',
style: TextStyle(
color: Colors.white,
),
),
onPressed: () => Navigator.pop(context, false),
),
TextButton(
child: Text('刪除',
style: TextStyle(
color: Colors.red[300],
)),
onPressed: () => Navigator.pop(context, true),
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: AppBar(
title: const Text('備忘錄'),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
decoration: InputDecoration(
hintText: '搜索備忘錄',
prefixIcon: const Icon(Icons.search),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4.0),
),
),
onChanged: (value) {
_refreshMemoList(searchKey: value);
},
),
),
Expanded(
child: ListView.builder(
itemCount: _memoList.length,
itemBuilder: (context, index) {
Memo memo = _memoList[index];
return ListTile(
title: Text(memo.title),
subtitle:
Text('${DateFormat.yMMMd().format(memo.modifiedTime)}更新'),
onTap: () {
_navigateToEditScreen(memo);
},
trailing: IconButton(
icon: const Icon(Icons.delete_forever_outlined),
onPressed: () {
_deleteMemo(memo);
},
),
);
},
),
),
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: Theme.of(context).primaryColor,
child: const Icon(Icons.add),
onPressed: () async {
_navigateToAddScreen();
},
),
);
}
_navigateToAddScreen() async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MemoAddScreen()),
);
if (result != null) {
_refreshMemoList();
}
}
_navigateToEditScreen(Memo memo) async {
final count = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => MemoEditScreen(memo: memo)),
);
if (count != null && count > 0) {
_refreshMemoList();
}
}
}列表頂部為一個(gè)搜索框,用于搜索備忘錄。備忘錄列表使用了 ListView,列表元素則使用了 ListTile 顯示標(biāo)題、更新時(shí)間和一個(gè)刪除按鈕。我們使用了 FloatingActionButton 來添加備忘錄。列表的業(yè)務(wù)邏輯如下:
- 進(jìn)入頁面從數(shù)據(jù)庫讀取備忘錄數(shù)據(jù);
- 點(diǎn)擊某一條備忘錄進(jìn)入編輯界面,編輯成功的話刷新界面;
- 點(diǎn)擊添加按鈕進(jìn)入添加界面,添加成功的話刷新界面;
- 點(diǎn)擊刪除按鈕刪除該條備忘錄,刪除前彈窗進(jìn)行二次確認(rèn);
- 搜索框內(nèi)容改變時(shí)從數(shù)據(jù)庫搜索備忘錄并根據(jù)搜索結(jié)果刷新界面。
- 刷新其實(shí)就是從數(shù)據(jù)庫讀取全部匹配的備忘錄數(shù)據(jù)后再通過 setState 更新列表數(shù)據(jù)。
添加頁面的代碼如下:
import 'package:flutter/material.dart';
import '../common/button_color.dart';
import 'memo_provider.dart';
class MemoAddScreen extends StatefulWidget {
const MemoAddScreen({Key? key}) : super(key: key);
@override
MemoAddScreenState createState() => MemoAddScreenState();
}
class MemoAddScreenState extends State<MemoAddScreen> {
final _formKey = GlobalKey<FormState>();
late String _title, _content;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('添加備忘錄'),
),
body: Builder(builder: (BuildContext context) {
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
decoration: const InputDecoration(labelText: '標(biāo)題'),
validator: (value) {
if (value == null || value.isEmpty) {
return '請輸入標(biāo)題';
}
return null;
},
onSaved: (value) {
_title = value!;
},
),
const SizedBox(height: 16),
TextFormField(
decoration: const InputDecoration(
labelText: '內(nèi)容',
alignLabelWithHint: true,
),
minLines: 10,
maxLines: null,
validator: (value) {
if (value == null || value.isEmpty) {
return '請輸入內(nèi)容';
}
return null;
},
onSaved: (value) {
_content = value!;
},
),
const SizedBox(height: 16),
ElevatedButton(
style: ButtonStyle(
backgroundColor: PrimaryButtonColor(
context: context,
),
),
onPressed: () async {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
var id = await saveMemo(context);
if (id > 0) {
_showSnackBar(context, '備忘錄已保存');
Navigator.of(context).pop(id);
} else {
_showSnackBar(context, '備忘錄保存失敗');
}
}
},
child: const Text(
'保 存',
style: TextStyle(color: Colors.black, fontSize: 16.0),
),
),
],
),
),
),
);
}),
);
}
Future<int> saveMemo(BuildContext context) async {
var createdTimestamp = DateTime.now().millisecondsSinceEpoch ~/ 1000;
var modifiedTimestamp = createdTimestamp;
var memoMap = {
'title': _title,
'content': _content,
'created_time': createdTimestamp,
'modified_time': modifiedTimestamp,
};
// 保存?zhèn)渫?
var id = await insertMemo(memoMap);
return id;
}
void _showSnackBar(BuildContext context, String message) async {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text(message)));
}
}添加頁面比較簡單,就兩個(gè)文本框加一個(gè)保存按鈕。在保存前對(duì)標(biāo)題和內(nèi)容進(jìn)行校驗(yàn),確保內(nèi)容不為空。在入庫前,讀取當(dāng)前時(shí)間并轉(zhuǎn)換為整數(shù)時(shí)間戳,構(gòu)建插入數(shù)據(jù)表的 Map 對(duì)象,然后執(zhí)行數(shù)據(jù)庫插入操作。成功的話給出提示信息并返回新插入的id到列表,失敗則只是顯示失敗信息。 通過列表和添加頁面我們可以看到,通過封裝方法后,其實(shí)讀寫數(shù)據(jù)庫的操作和通過接口獲取數(shù)據(jù)差不多,因此,如果說需要兼容數(shù)據(jù)庫和接口數(shù)據(jù),可以統(tǒng)一接口形式,這樣可以實(shí)現(xiàn)無縫切換。
運(yùn)行結(jié)果
我們來看看運(yùn)行結(jié)果,如下圖所示。完整代碼已經(jīng)上傳到:https://gitee.com/island-coder/flutter-beginner/tree/master/local_storage。

總結(jié)
本篇通過一個(gè)完整的備忘錄實(shí)例講解了在 Flutter 中如何使用 sqflite 實(shí)現(xiàn)結(jié)構(gòu)化數(shù)據(jù)本地存儲(chǔ)。在實(shí)際的 App 開發(fā)中,我們會(huì)經(jīng)常遇到需要將大量的數(shù)據(jù)進(jìn)行本地化存儲(chǔ)的需求。備忘錄是典型的一種,還有諸如記賬、筆記、資訊、即時(shí)聊天等等應(yīng)用都會(huì)有類似的需求。相信通過本篇,能讓 Flutter 開發(fā)同學(xué)應(yīng)對(duì)基礎(chǔ)的結(jié)構(gòu)化存儲(chǔ)的業(yè)務(wù)開發(fā)。
到此這篇關(guān)于Android Flutter使用本地?cái)?shù)據(jù)庫編寫備忘錄應(yīng)用的文章就介紹到這了,更多相關(guān)Android Flutter備忘錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android Studio實(shí)現(xiàn)下拉列表效果
這篇文章主要為大家詳細(xì)介紹了Android Studio實(shí)現(xiàn)下拉列表效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
android實(shí)現(xiàn)多點(diǎn)觸摸應(yīng)用
這篇文章主要為大家詳細(xì)介紹了android實(shí)現(xiàn)多點(diǎn)觸摸應(yīng)用,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05
Android編程錄音工具類RecorderUtil定義與用法示例
這篇文章主要介紹了Android編程錄音工具類RecorderUtil定義與用法,結(jié)合實(shí)例形式分析了Android錄音工具類實(shí)現(xiàn)開始錄音、停止錄音、取消錄音、獲取錄音信息等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Android模仿To圈兒個(gè)人資料界面層疊淡入淡出顯示效果
這篇文章主要介紹了Android模仿To圈兒個(gè)人資料界面層疊淡入淡出顯示效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-07-07
Android Coil對(duì)比Glide深入分析探究
這篇文章主要介紹了Android Coil對(duì)比Glide,Coil是Android上的一個(gè)全新的圖片加載框架,它的全名叫做coroutine image loader,即協(xié)程圖片加載庫2023-02-02

