Android?Flutter使用本地數(shù)據(jù)庫編寫備忘錄應用
前言
前面一篇我們介紹了使用 shared_preferences
實現(xiàn)簡單的鍵值對存儲,然而我們還會面臨更為復雜的本地存儲。比如資訊類 App會緩存一部分上次加載的內(nèi)容,在沒有網(wǎng)絡的情況下也能夠提供內(nèi)容;比如微信的聊天記錄都是存儲在手機客戶端。當我們需要在本地存儲大量結構化的數(shù)據(jù)的時候,使用 shared_preferences
顯然是不夠的。這個時候我們就需要使用本地數(shù)據(jù)庫,移動端最為常用的本地數(shù)據(jù)庫是 SQLite。在 Flutter中同樣提供了對 SQLite 的支持,我們可以使用 sqflite
這個插件搞定結構化數(shù)據(jù)的本地存儲。本篇我們以一個完整的備忘錄的實例來講述如何使用 sqflite
。
業(yè)務需求解讀
我們先來看備忘錄的功能:
- 顯示已經(jīng)記錄的備忘錄列表,按更新時間倒序排序;
- 按標題或內(nèi)容搜索備忘錄;
- 添加備忘錄,并保存在本地;
- 編輯備忘錄,成功后更新原有備忘錄;
- 刪除備忘錄;
- 備忘錄通常包括標題、內(nèi)容、創(chuàng)建時間和更新時間這些屬性。
可以看到,這其實是一個典型的數(shù)據(jù)表的 CRUD 操作。
實體類設計
我們設計一個 Memo類,包括了 id、標題、內(nèi)容、創(chuàng)建時間和更新時間5個屬性,用來代表一個備忘錄。同時提供了兩個方法,以便和數(shù)據(jù)庫操作層面對接。代碼如下:
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), ); } }
這里說一下,因為 SQLite 的時間戳(為1970-01-01以來的秒數(shù))只能以整數(shù)存儲,因此我們需要在入庫操作(toMap
)時 DateTime
轉(zhuǎn)換為整數(shù)時間戳,在 出庫時(fromMap
)將時間戳轉(zhuǎn)換為 DateTime
。
數(shù)據(jù)庫工具類
我們寫一個基礎的數(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)、浮點數(shù)(REAL)、文本(TEXT)、BLOB(二進制格式,如存儲文件)。
備忘錄數(shù)據(jù)表訪問接口
我們?yōu)閭渫浱峁┮粋€數(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 提供了如下方法來支持數(shù)據(jù)庫操作:
insert
:向指定數(shù)據(jù)表插入數(shù)據(jù),需要提供表名和對應的數(shù)據(jù),其中數(shù)據(jù)為Map
類型,鍵名為數(shù)據(jù)表的字段名。成功后會返回插入數(shù)據(jù)的id
。update
:按where
條件更新數(shù)據(jù)表數(shù)據(jù),where
條件分為兩個參數(shù),一個是where
表達式,其中變量使用?
替代,另一個是whereArgs
參數(shù)列表,多個參數(shù)使用數(shù)據(jù)傳遞,用于替換表達式的?
通配符。where
條件支持如等于、大于小于、大于等于、小于等于、NOT、AND、OR、LIKE、BETWEEN 等,具體大家可以去搜一下。delete
:刪除where
條件指定的數(shù)據(jù),不可恢復。query
:查詢,按指定條件查詢數(shù)據(jù),支持按字段使用orderBy
屬性進行排序。這里我們使用了LIKE
來搜索匹配的標題或內(nèi)容。
UI 界面實現(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('確定要刪除 "${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(); } } }
列表頂部為一個搜索框,用于搜索備忘錄。備忘錄列表使用了 ListView
,列表元素則使用了 ListTile
顯示標題、更新時間和一個刪除按鈕。我們使用了 FloatingActionButton
來添加備忘錄。列表的業(yè)務邏輯如下:
- 進入頁面從數(shù)據(jù)庫讀取備忘錄數(shù)據(jù);
- 點擊某一條備忘錄進入編輯界面,編輯成功的話刷新界面;
- 點擊添加按鈕進入添加界面,添加成功的話刷新界面;
- 點擊刪除按鈕刪除該條備忘錄,刪除前彈窗進行二次確認;
- 搜索框內(nèi)容改變時從數(shù)據(jù)庫搜索備忘錄并根據(jù)搜索結果刷新界面。
- 刷新其實就是從數(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: '標題'), validator: (value) { if (value == null || value.isEmpty) { return '請輸入標題'; } 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))); } }
添加頁面比較簡單,就兩個文本框加一個保存按鈕。在保存前對標題和內(nèi)容進行校驗,確保內(nèi)容不為空。在入庫前,讀取當前時間并轉(zhuǎn)換為整數(shù)時間戳,構建插入數(shù)據(jù)表的 Map
對象,然后執(zhí)行數(shù)據(jù)庫插入操作。成功的話給出提示信息并返回新插入的id
到列表,失敗則只是顯示失敗信息。 通過列表和添加頁面我們可以看到,通過封裝方法后,其實讀寫數(shù)據(jù)庫的操作和通過接口獲取數(shù)據(jù)差不多,因此,如果說需要兼容數(shù)據(jù)庫和接口數(shù)據(jù),可以統(tǒng)一接口形式,這樣可以實現(xiàn)無縫切換。
運行結果
我們來看看運行結果,如下圖所示。完整代碼已經(jīng)上傳到:https://gitee.com/island-coder/flutter-beginner/tree/master/local_storage。
總結
本篇通過一個完整的備忘錄實例講解了在 Flutter 中如何使用 sqflite
實現(xiàn)結構化數(shù)據(jù)本地存儲。在實際的 App 開發(fā)中,我們會經(jīng)常遇到需要將大量的數(shù)據(jù)進行本地化存儲的需求。備忘錄是典型的一種,還有諸如記賬、筆記、資訊、即時聊天等等應用都會有類似的需求。相信通過本篇,能讓 Flutter 開發(fā)同學應對基礎的結構化存儲的業(yè)務開發(fā)。
到此這篇關于Android Flutter使用本地數(shù)據(jù)庫編寫備忘錄應用的文章就介紹到這了,更多相關Android Flutter備忘錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Android編程錄音工具類RecorderUtil定義與用法示例
這篇文章主要介紹了Android編程錄音工具類RecorderUtil定義與用法,結合實例形式分析了Android錄音工具類實現(xiàn)開始錄音、停止錄音、取消錄音、獲取錄音信息等相關操作技巧,需要的朋友可以參考下2018-01-01