上一篇讲了文件存储
path_provider
的使用,今天接着学习第三种数据存储方式:Sqlite3
。在Flutter中的数据库叫Sqflite
跟原生安卓的Sqlite叫法不一样。我们来看下Sqflite官方对它的解释说明:
SQLite plugin for Flutter. Supports both iOS and Android.
Support transactions and batches
Automatic version managment during open
Helpers for insert/query/update/delete queries
DB operation executed in a background thread on iOS and Android
Sqflite的使用
通过上面的描述,我们了解到Sqflite是一个同时支持Android跟Ios平台的数据库,并且支持标准的CURD操作,下面我们还是用上面操作文件跟sp的代码逻辑是一块体验一下Sqflite。
同样需要引入依赖:
#添加Sqflite依赖
sqflite: ^1.0.0
然后命令行执行flutter packages get
完成后如下:
数据存取示例
模拟场景:
利用
Sqflite
创建一张user
表,其中user
表中id
设置为主键id
,且为自增长,name
字段为text类型,用户按下存储按钮后,把TextFile
输入框里的内容插入到user
表中,当按下获取按钮时,取出数据库中最后一条数据显示在下方Text
上,并且显示出当前数据库中一共有多少条数据,以及数据库的存储路径。
效果图:
终端输出: 我存了4次,所以有四个输出。
I/flutter (28891): ----------------[{id: 1, name: userlzz}, {id: 2, name: userlzz1}]
I/flutter (28891): ----------------[{id: 1, name: userlzz}, {id: 2, name: userlzz1}, {id: 3, name: userlzz2}]
I/flutter (28891): ----------------[{id: 1, name: userlzz}, {id: 2, name: userlzz1}, {id: 3, name: userlzz2}]
I/flutter (28891): ----------------[{id: 1, name: userlzz}, {id: 2, name: userlzz1}, {id: 3, name: userlzz2}, {id: 4, name: userlzz3}]
示例代码
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class SqfliteTest extends StatefulWidget {
SqfliteTest({Key key, this.title}) : super(key: key);
final String title;
@override
createState() => new _SqfliteTestState();
}
class _SqfliteTestState extends State<SqfliteTest> {
var _textFieldController = new TextEditingController();
var _storageString = '';
/**
* 利用Sqflite数据库存储数据
*/
saveString() async {
final db = await getDataBase('my_db.db');
//写入字符串
print('user 是表名!!');
db.transaction((trx) {
trx.rawInsert(
'INSERT INTO user(name) VALUES("${_textFieldController.value.text.toString()}")');
});
}
/**
* 获取存在Sqflite数据库中的数据
*/
Future getString() async {
final db = await getDataBase('my_db.db');
var dbPath = db.path;
setState(() {
db.rawQuery('SELECT * FROM user').then((List<Map> lists) {
print('----------------$lists');
var listSize = lists.length;
//获取数据库中的最后一条数据
_storageString = lists[listSize - 1]['name'] +
"\n现在数据库中一共有${listSize}条数据" +
"\n数据库的存储路径为${dbPath}";
});
});
}
/**
* 初始化数据库存储路径
*/
Future<Database> getDataBase(String dbName) async {
//获取应用文件目录类似于Ios的NSDocumentDirectory和Android上的 AppData目录
final fileDirectory = await getApplicationDocumentsDirectory();
//获取存储路径
final dbPath = fileDirectory.path;
//构建数据库对象
Database database = await openDatabase(dbPath + "/" + dbName, version: 1,
onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT)");
});
return database;
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('数据库Sqflite'),
),
body: new Column(
children: <Widget>[
SizedBox(height: 5,),
Text("数据库Sqflite存储", textAlign: TextAlign.center,style: TextStyle(fontSize: 28,color: Colors.deepOrange),),
Container(
padding: EdgeInsets.all(10),
height: 58,
child: TextField(
controller: _textFieldController,
style: TextStyle(fontSize: 28),
),
),
MaterialButton(
onPressed: saveString,
child: new Text("存储",style: TextStyle(color: Colors.white,fontSize: 22),),
color: Colors.lightBlueAccent,
),
MaterialButton(
onPressed: getString,
child: new Text("获取",style: TextStyle(color: Colors.white,fontSize: 22),),
color: Colors.lightGreen,
),
SizedBox(height: 15,),
Text('存储的值为:$_storageString',style: TextStyle(fontSize: 22,color: Colors.deepOrange)),
],
),
);
}
}
至此,三种最常用的数据存储方式讲完了,要想在实战使用,还需要多加练习。