Flutter 本地数据库sqflite实战操作
通过本文章将带你了解sqflite如何使用并管理,注意要学习本功能、要具备一定的sql数据库操作的基础知识!
知识点:
- 本地化列表数据
- 本地化列表详情数据
- sqflite 本地化数据库增删改查操作
一、安装sqflite
https://pub.flutter-io.cn/packages/sqflite
二、创建Db数据库文件夹,创建Db文件
文件夹路径:Lib/Db/StepTasksDb/StepTasksDb.dart
三、编辑Db文件
StepTasksDb.dart全部代码
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
final String tableName = 'step_task_table';
final String columnId = '_id';
final String columnType = 'step_listType';
final String columnStepListData = 'step_listData';
final String columnStepDataDetails = 'step_status';
class StepTasks {
int id;
String stepListType;
String stepListData;
String stepDataDetails;
StepTasks({this.id, this.stepListType, this.stepListData, this.stepDataDetails});
Map<String, Object> toMap() {
var map = <String ,Object>{
columnType:stepListType,
columnStepListData:stepListData,
columnStepDataDetails:stepDataDetails
};
if (id != null) {
map[columnId] = id;
}
return map;
}
StepTasks.fromMap(Map<String, Object> map){
id = map[columnId];
stepListType = map[columnType];
stepListData = map[columnStepListData];
stepDataDetails = map[columnStepDataDetails];
}
}
class StepTasksDb {
Database db;
Future<String> initDatabase() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'stepTasks.db');
return path;
}
Future open(String path) async {
print('------------------打开并创建表<StepTasksDb>------------------');
db = await openDatabase(path, version:1, onCreate:(Database db, int version) async {
await db.execute('''
create table $tableName (
$columnId integer primary key autoincrement,
$columnType text ,
$columnStepListData text ,
$columnStepDataDetails text
)
''');
});
}
Future<StepTasks> insert(StepTasks data) async {
data.id = await db.insert(tableName, data.toMap());
return data;
}
Future<List> getData({type = ''}) async {
List<Map> maps = [];
maps = await db.query(tableName, columns:[columnId, columnType, columnStepListData, columnStepDataDetails], where: '$columnType = ?', whereArgs: [type]);
if(maps ==null || maps.length == 0){
return [];
}
List list = [];
for(int i = 0; i<maps.length; i++){
list.add(maps[i]);
}
return list;
}
Future<int> update(StepTasks data) async {
return await db.update(tableName, data.toMap(), where: '$columnId = ?', whereArgs: [data.id]);
}
Future<int> delete(int id) async {
return await db.delete(tableName, where:'$columnId = ?', whereArgs:[id]);
}
Future close() async => db.close();
}
四、使用创建的数据库文件
注意: 首先安装网络监听插件:connectivity,虽然本插件已经停止更新了,但是在Pub官方文档也有新的插件替代了旧插件,大家可以凭个人需求来,这里不强求用什么插件,只需要达到网络监听效果即可。
import 'dart:convert';
import 'package:flutter/material.dart';
import 'TestDb_Flutter/Db/StepTasksDb/StepTasksDb.dart';
class TestDbPage extends StatefulWidget {
@override
State<TestDbPage> createState() => _TestDbPageState();
}
class _TestDbPageState extends State<TestDbPage> {
var listData = [];
var _storageListData = [];
List cacheSelectList = [];
var networkStatus = -1;
StepTasksDb _stepTaskDb = StepTasksDb();
@override
void initState() {
super.initState();
_initDatabase();
}
Future _initDatabase() async {
String path = await _stepTaskDb.initDatabase();
await _stepTaskDb.open(path);
_getListData();
}
Future _getListData() async {
await _getStorageData();
if(networkStatus == 1){
var res = await api.request('https://xxx.xxxx/api');
setState((){listData = res['data']})
return res;
}else{
setState(() {
_listData = _storageListData;
});
return _storageListData;
}
}
Future _getStorageData() async {
var data = await _stepTaskDb.getData(type: 'process');
setState(() {
_storageListData = data;
});
}
@override
void dispose() {
_stepTaskDb.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: listData.length,
itemBuilder: (context, index){
return InkWell(
child:Container(child:Text(listData[index]['title']));
onTap:(){
var dataBase = {
'step_listData': json.encode(listData[index]),
};
var params = {id:'xxx'};
var res = await api.request('https://xxx.xxxx/api', formData: params);
if(res != null){
dataBase['assets_listDetails'] = json.encode(res['data']);
}
var db_res = await _stepTaskDb.insert(StepTasks(stepListType:'process', stepListData:dataBase['step_listData'], stepDataDetails:dataBase['assets_listDetails']));
},
onLongPress: (){
_stepTaskDb.delete(v['_id']);
},
);
},
);
}
}
以上代码暂且只介绍了本地化操作的 增删查操作、至于修改操作,则和增操作大体类似,通过传入的本地数据id,来将新的数据替换掉旧的数据即可
例子:
var res = await _stepTaskDb.update(StepTasks(id:v['id'], stepListType:'process', stepListData:dataBase['listData'], stepDataDetails:dataBase['listDetails']));
目前为止,应该将最基本的增删改查操作介绍完了,并且附上了例子,如果不出大问题的话,大家应该可以达到本地化数据的操作,有问题请下方留言联系我~
|