Future<Database> _initDB(String filePath) async { final dbPath = await getDatabasesPath(); final path = join(dbPath, filePath); return await openDatabase(path, version: 1, onCreate: _createDB); }同时 sqflite 提供了一个方法来获取当前数据库的版本。
var version = await db.getVersion();有了这个,我们就可以判断当前本地的数据库版本是不是最新版本了。在 sqflite 中,提供了版本升级的处理方法,当检测到 version 参数比当前的数据库版本高时,就可以执行 onUpgrade 方法,在这个方法里可以处理数据表升级操作,比如增加/删除字段,更改字段默认值等。
var db = await openDatabase(path, version: latestVersion, onCreate: _createDB, onUpgrade: _updateDB);备忘录实例 - 增加标签
Future<void> _updateDB(Database db, int oldVersion, int newVersion) async { try { await db.execute('ALTER TABLE memo ADD COLUMN tags TEXT'); } on DatabaseException catch (e) { if (e.isDuplicateColumnError()) { // 堆代码 duidaima.com // 忽略该异常,该列已经存在 } else { rethrow; } } await db.setVersion(newVersion); }这里之所以捕获异常,是因为添加字段操作不允许添加已有的字段,如果发生了重复字段异常处理我们忽略这个异常,已让程序能够正常运行。这里需要注意,在创建数据表的时候也需要更改SQL,增加 tags 字段(upgrade方法只对旧版本的做升级处理,不会更改现有版本的数据表)。
Future<void> _createDB(Database db, int version) async { await db.execute(''' CREATE TABLE memo ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT, tags TEXT, created_time INTEGER, modified_time INTEGER ) '''); }接下来是备忘录的代码实现,我们用 InputChip定义了一个标签组件,以支持能够通过删除图标删掉标签。
class Tag extends StatelessWidget { final String text; final VoidCallback onDeleted; const Tag({Key? key, required this.text, required this.onDeleted}) : super(key: key); @override Widget build(BuildContext context) { return InputChip( label: Text(text), onDeleted: onDeleted, ); } }在添加备忘录的页面中,在表单区增加了如下内容,一个 Wrap 组件来显示多个标签,然后一个输入框来添加标签。
Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Wrap( alignment: WrapAlignment.start, spacing: 4.0, runSpacing: 4.0, children: [ for (final tag in _tags) Tag( text: tag, onDeleted: () => _removeTag(tag), ) ], ), TextField( controller: _tagController, decoration: InputDecoration( labelText: '添加标签', suffixIcon: IconButton( icon: const Icon(Icons.add), onPressed: _addTag, ), ), onSubmitted: (_) => _addTag(), ), ], ),当添加标签时,就往标签数组里增加标签字符串元素,删除标签时就移除该标签。这里注意,为了避免标签重复,添加标签时需要检查当前标签是否已经存在。
void _addTag() { final newTag = _tagController.text.trim(); if (newTag.isNotEmpty && !_tags.contains(newTag)) { setState(() { _tags.add(newTag); _tagController.clear(); }); } }之后就是更改我们的保存备忘录的方法。
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, 'tags': _tags.isNotEmpty ? _tags.join('|') : '', }; // 保存备忘录 var id = await insertMemo(memoMap); return id; }运行效果
本篇介绍了 Flutter 使用 sqflite 处理数据表变更的版本升级处理方法。当我们使用数据库在 App 里存储本地结构化数据的时候,不可避免会遇到新增字段、删除字段等的处理吗,这个时候就需要进行数据库版本升级操作。
在 sqflite 中,会自动根据本地的数据库版本和当前的数据库版本进行对比,如果本地版本低于当前的数据库版本就会调用 onUpgrade 方法处理版本升级,比如字段变更,数据迁移等。同时,大家做本地数据库的时候,务必注意不同版本之间的兼容,一方面是尽可能地保持数据表不变更,另一方面是做好不同版本的升级和数据迁移工作。