软件编程
位置:首页>> 软件编程>> flutter编程>> Android Flutter使用本地数据库编写备忘录应用

Android Flutter使用本地数据库编写备忘录应用

作者:岛上码农  发布时间:2023-09-15 17:24:09 

标签:Android,Flutter,备忘录

前言

前面一篇我们介绍了使用 shared_preferences实现简单的键值对存储,然而我们还会面临更为复杂的本地存储。比如资讯类 App会缓存一部分上次加载的内容,在没有网络的情况下也能够提供内容;比如微信的聊天记录都是存储在手机客户端。当我们需要在本地存储大量结构化的数据的时候,使用 shared_preferences 显然是不够的。这个时候我们就需要使用本地数据库,移动端最为常用的本地数据库是 SQLite。在 Flutter中同样提供了对 SQLite 的支持,我们可以使用 sqflite 这个插件搞定结构化数据的本地存储。本篇我们以一个完整的备忘录的实例来讲述如何使用 sqflite

业务需求解读

我们先来看备忘录的功能:

  • 显示已经记录的备忘录列表,按更新时间倒序排序;

  • 按标题或内容搜索备忘录;

  • 添加备忘录,并保存在本地;

  • 编辑备忘录,成功后更新原有备忘录;

  • 删除备忘录;

  • 备忘录通常包括标题、内容、创建时间和更新时间这些属性。

可以看到,这其实是一个典型的数据表的 CRUD 操作。

实体类设计

我们设计一个 Memo类,包括了 id、标题、内容、创建时间和更新时间5个属性,用来代表一个备忘录。同时提供了两个方法,以便和数据库操作层面对接。代码如下:

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以来的秒数)只能以整数存储,因此我们需要在入库操作(toMap)时 DateTime 转换为整数时间戳,在 出库时(fromMap)将时间戳转换为 DateTime

数据库工具类

我们写一个基础的数据库工具类,主要是初始化数据库和创建数据表,代码如下:

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

创建数据表的语法和 MySQL 基本上是一样的,需要注意的是字段类型没有 MySQL 丰富,只支持简单的整数(INTEGER)、浮点数(REAL)、文本(TEXT)、BLOB(二进制格式,如存储文件)。

备忘录数据表访问接口

我们为备忘录提供一个数据库的通用的访问接口,包括了插入、更新、删除和读取备忘录的方法。

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 提供了如下方法来支持数据库操作:

  • insert:向指定数据表插入数据,需要提供表名和对应的数据,其中数据为 Map 类型,键名为数据表的字段名。成功后会返回插入数据的 id

  • update:按 where 条件更新数据表数据,where 条件分为两个参数,一个是 where 表达式,其中变量使用?替代,另一个是 whereArgs 参数列表,多个参数使用数据传递,用于替换表达式的?通配符。where条件支持如等于、大于小于、大于等于、小于等于、NOT、AND、OR、LIKE、BETWEEN 等,具体大家可以去搜一下。

  • delete:删除where条件指定的数据,不可恢复。

  • query:查询,按指定条件查询数据,支持按字段使用orderBy属性进行排序。这里我们使用了 LIKE 来搜索匹配的标题或内容。

UI 界面实现

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 来添加备忘录。列表的业务逻辑如下:

  • 进入页面从数据库读取备忘录数据;

  • 点击某一条备忘录进入编辑界面,编辑成功的话刷新界面;

  • 点击添加按钮进入添加界面,添加成功的话刷新界面;

  • 点击删除按钮删除该条备忘录,删除前弹窗进行二次确认;

  • 搜索框内容改变时从数据库搜索备忘录并根据搜索结果刷新界面。

  • 刷新其实就是从数据库读取全部匹配的备忘录数据后再通过 setState 更新列表数据。

添加页面的代码如下:

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: '内容',
                     alignLabelWithHint: true,
                   ),
                   minLines: 10,
                   maxLines: null,
                   validator: (value) {
                     if (value == null || value.isEmpty) {
                       return '请输入内容';
                     }
                     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,
   };
   // 保存备忘录
   var id = await insertMemo(memoMap);
   return id;
 }
void _showSnackBar(BuildContext context, String message) async {
   ScaffoldMessenger.of(context)
       .showSnackBar(SnackBar(content: Text(message)));
 }
}

添加页面比较简单,就两个文本框加一个保存按钮。在保存前对标题和内容进行校验,确保内容不为空。在入库前,读取当前时间并转换为整数时间戳,构建插入数据表的 Map 对象,然后执行数据库插入操作。成功的话给出提示信息并返回新插入的id到列表,失败则只是显示失败信息。 通过列表和添加页面我们可以看到,通过封装方法后,其实读写数据库的操作和通过接口获取数据差不多,因此,如果说需要兼容数据库和接口数据,可以统一接口形式,这样可以实现无缝切换。

运行结果

我们来看看运行结果,如下图所示。完整代码已经上传到:https://gitee.com/island-coder/flutter-beginner/tree/master/local_storage。

来源:https://juejin.cn/post/7214854106178355255

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com