当前位置:网站首页>Use of shutter SQLite
Use of shutter SQLite
2022-07-01 13:13:00 【xiangxiongfly915】
List of articles
Flutter SQLite Use
summary
Saving data locally is one of the most important functions of an application , For example, the following scenes : A news or blog application , Open it and go to the home page , If the data is not saved locally , You need to get data through the Internet , Before returning data , What the user sees is a blank page , And if you keep some news locally , This part of the data is displayed , When waiting for the latest data to return, refresh it , For the user experience , Obviously the second experience is better .
SQLite Is currently one of the most popular local storage frameworks .
Add dependency
dependencies:
path_provider: ^2.0.11
sqflite: ^2.0.2+1
Use SQLite
Use a singleton class
class DBManager {
static final DBManager _instance = DBManager._internal();
factory DBManager() {
return _instance;
}
DBManager._internal();
}
initialization
class DBManager {
static Database? _db;
Future<Database?> get db async {
// if (_db != null) {
// return _db;
// }
// _db = await _initDB();
// return _db;
return _db ??= await _initDB();
}
/// Initialize database
Future<Database> _initDB() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, "dbName");
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
onUpgrade: _onUpgrade,
);
}
/// Create table
Future _onCreate(Database db, int version) async {
const String sql = """
CREATE TABLE Student(
id INTEGER primary key AUTOINCREMENT,
name TEXT,
age INTEGER,
sex INTEGER
)
""";
return await db.execute(sql);
}
/// Update table
Future _onUpgrade(Database db, int oldVersion, int newVersion) async {}
}
Add, delete, change and check operation
/// Save the data
Future saveData(Student student) async {
var _db = await db;
return await _db?.insert("Student", student.toJson());
}
/// Use SQL Save the data
Future saveDataBySQL(Student student) async {
const String sql = """
INSERT INTO Student(name,age,sex) values(?,?,?)
""";
var _db = await db;
return await _db?.rawInsert(sql, [student.name, student.age, student.sex]);
}
/// Query all data
Future<List<Student>?> findAll() async {
var _db = await db;
List<Map<String, Object?>>? result = await _db?.query("Student");
if (result == null) {
return null;
} else {
if (result.isNotEmpty) {
return result.map((e) => Student.fromJson(e)).toList();
} else {
return [];
}
}
}
/// Conditions of the query
Future<List<Student>?> find(int sex) async {
var _db = await db;
List<Map<String, dynamic>>? result = await _db?.query("Student", where: "sex=?", whereArgs: [sex]);
if (result == null) {
return null;
} else {
if (result.isNotEmpty) {
return result.map((e) => Student.fromJson(e)).toList();
} else {
return [];
}
}
}
/// modify
Future<int> update(Student student) async {
var _db = await db;
student.age = 99;
int? count = await _db?.update("Student", student.toJson(), where: "id=?", whereArgs: [student.id]);
return count ?? 0;
}
/// Delete
Future<int> delete(int id) async {
var _db = await db;
int? count = await _db?.delete("Student", where: "id=?", whereArgs: [id]);
return count ?? 0;
}
/// Delete all
Future<int> deleteAll() async {
var _db = await db;
int? count = await _db?.delete("Student");
return count ?? 0;
}
The complete code is as follows



Database management class
class DBManager {
static final DBManager _instance = DBManager._internal();
factory DBManager() {
return _instance;
}
DBManager._internal();
static Database? _db;
Future<Database?> get db async {
// if (_db != null) {
// return _db;
// }
// _db = await _initDB();
// return _db;
return _db ??= await _initDB();
}
/// Initialize database
Future<Database> _initDB() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, "dbName");
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
onUpgrade: _onUpgrade,
);
}
/// Create table
Future _onCreate(Database db, int version) async {
const String sql = """
CREATE TABLE Student(
id INTEGER primary key AUTOINCREMENT,
name TEXT,
age INTEGER,
sex INTEGER
)
""";
return await db.execute(sql);
}
/// Update table
Future _onUpgrade(Database db, int oldVersion, int newVersion) async {}
/// Save the data
Future saveData(Student student) async {
var _db = await db;
return await _db?.insert("Student", student.toJson());
}
/// Use SQL Save the data
Future saveDataBySQL(Student student) async {
const String sql = """
INSERT INTO Student(name,age,sex) values(?,?,?)
""";
var _db = await db;
return await _db?.rawInsert(sql, [student.name, student.age, student.sex]);
}
/// Query all data
Future<List<Student>?> findAll() async {
var _db = await db;
List<Map<String, Object?>>? result = await _db?.query("Student");
if (result == null) {
return null;
} else {
if (result.isNotEmpty) {
return result.map((e) => Student.fromJson(e)).toList();
} else {
return [];
}
}
}
/// Conditions of the query
Future<List<Student>?> find(int age) async {
var _db = await db;
List<Map<String, dynamic>>? result = await _db?.query("Student", where: "age=?", whereArgs: [age]);
if (result == null) {
return null;
} else {
if (result.isNotEmpty) {
return result.map((e) => Student.fromJson(e)).toList();
} else {
return [];
}
}
}
/// modify
Future<int> update(Student student) async {
var _db = await db;
student.age = 99;
int? count = await _db?.update("Student", student.toJson(), where: "id=?", whereArgs: [student.id]);
return count ?? 0;
}
/// Delete
Future<int> delete(int id) async {
var _db = await db;
int? count = await _db?.delete("Student", where: "id=?", whereArgs: [id]);
return count ?? 0;
}
/// Delete all
Future<int> deleteAll() async {
var _db = await db;
int? count = await _db?.delete("Student");
return count ?? 0;
}
}
Defining entity classes
Student studentFromJson(String str) => Student.fromJson(json.decode(str));
String studentToJson(Student data) => json.encode(data.toJson());
class Student {
Student({
this.id,
this.name,
this.age,
this.sex,
});
Student.fromJson(dynamic json) {
id = json['id'];
name = json['name'];
age = json['age'];
sex = json['sex'];
}
int? id;
String? name;
int? age;
int? sex;
Map<String, dynamic> toJson() {
final map = <String, dynamic>{};
map['id'] = id;
map['name'] = name;
map['age'] = age;
map['sex'] = sex;
return map;
}
}
Home code
class SqlitePage extends StatefulWidget {
const SqlitePage({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _SqlitePageState();
}
}
class _SqlitePageState extends State<SqlitePage> {
List<Student>? _studentList;
loadAllData() async {
_studentList = await DBManager().findAll();
setState(() {});
}
loadData() async {
_studentList = await DBManager().find(1);
setState(() {});
}
updateData(Student student) async {
var count = await DBManager().update(student);
if (count > 0) {
showSnackBar(context, " Modification successful ");
} else {
showSnackBar(context, " Modification failed ");
}
}
deleteData(int id) async {
var count = await DBManager().delete(id);
if (count > 0) {
showSnackBar(context, " Delete successful ");
} else {
showSnackBar(context, " Delete failed ");
}
}
deleteAllData() async {
var count = await DBManager().deleteAll();
if (count > 0) {
showSnackBar(context, " Delete successful ");
} else {
showSnackBar(context, " Delete failed ");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("SQLite"),
actions: [
IconButton(
icon: const Icon(Icons.add),
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return const AddStudentPage();
}));
},
)
],
),
body: SingleChildScrollView(
child: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () {
loadAllData();
},
child: const Text(" Query all the data "),
),
ElevatedButton(
onPressed: () {
loadData();
},
child: const Text(" Conditions of the query "),
),
ElevatedButton(
onPressed: () {
deleteAllData();
},
child: const Text(" Delete all "),
),
Padding(
padding: const EdgeInsets.all(10),
child: _buildTable(),
),
],
),
),
),
);
}
_buildTable() {
return Table(
border: TableBorder.all(),
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: [
const TableRow(children: [
TableCell(child: Text("id")),
TableCell(child: Text(" full name ")),
TableCell(child: Text(" Age ")),
TableCell(child: Text(" Gender ")),
TableCell(child: Text(" modify ")),
TableCell(child: Text(" Delete ")),
]),
...?_studentList
?.map((e) => TableRow(children: [
TableCell(child: Text("${e.id}")),
TableCell(child: Text("${e.name}")),
TableCell(child: Text("${e.age}")),
TableCell(child: Text("${e.sex}")),
TableCell(
child: TextButton(
onPressed: () {
updateData(e);
},
child: const Text(" modify "),
),
),
TableCell(
child: TextButton(
onPressed: () {
deleteData(e.id!);
},
child: const Text(" Delete "),
),
),
]))
.toList(),
],
);
}
}
Add data pages
class AddStudentPage extends StatefulWidget {
const AddStudentPage({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _AddStudentPageState();
}
}
class _AddStudentPageState extends State<AddStudentPage> {
int _sexValue = 0;
late TextEditingController _nameController;
late TextEditingController _ageController;
@override
void initState() {
_nameController = TextEditingController();
_ageController = TextEditingController();
super.initState();
}
@override
void dispose() {
_nameController.dispose();
_ageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(" Add students "),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
TextField(
controller: _nameController,
decoration: const InputDecoration(labelText: " full name :"),
),
TextField(
controller: _ageController,
decoration: const InputDecoration(labelText: " Age :"),
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
],
),
Row(
children: [
Expanded(
child: RadioListTile<int>(
title: const Text(" Woman "),
value: 0,
groupValue: _sexValue,
onChanged: (value) {
setState(() {
_sexValue = value!;
});
},
),
),
Expanded(
child: RadioListTile<int>(
title: const Text(" male "),
value: 1,
groupValue: _sexValue,
onChanged: (value) {
setState(() {
_sexValue = value!;
});
},
),
),
],
),
Builder(builder: (BuildContext context) {
return Column(
children: [
ElevatedButton(
onPressed: () async {
var student = Student(
name: _nameController.text.toString(),
age: int.parse(_ageController.text.toString()),
sex: _sexValue,
);
int result = await DBManager().saveData(student);
if (result > 0) {
showSnackBar(context, ' Data saved successfully ,result:$result');
} else {
showSnackBar(context, ' Failed to save data ,result:$result');
}
},
child: const Text(" Save the data "),
),
ElevatedButton(
onPressed: () async {
var student = Student(
name: _nameController.text.toString(),
age: int.parse(_ageController.text.toString()),
sex: _sexValue,
);
int result = await DBManager().saveDataBySQL(student);
if (result > 0) {
showSnackBar(context, ' Data saved successfully ,result:$result');
} else {
showSnackBar(context, ' Failed to save data ,result:$result');
}
},
child: const Text(" Use SQL Save the data "),
),
],
);
}),
],
),
),
);
}
}
边栏推荐
- VM虚拟机配置动态ip和静态ip访问
- Svg diamond style code
- MySQL statistical bill information (Part 2): data import and query
- 快速整明白Redis中的压缩列表到底是个啥
- 请问flink mysql cdc 全量读取mysql某个表数据,对原始的mysql数据库有影响吗
- [encounter Django] - (II) database configuration
- Redis exploration: cache breakdown, cache avalanche, cache penetration
- Simple two ball loading
- Sharing with the best paper winner of CV Summit: how is a good paper refined?
- R language uses conf of yardstick package_ The mat function calculates the confusion matrix of the multiclass model on each fold of each cross validation (or resampling), and uses the summary to outpu
猜你喜欢

王兴的无限游戏迎来“终极”一战

Vs code setting Click to open a new file window without overwriting the previous window

图灵奖得主Judea Pearl:最近值得一读的19篇因果推断论文

Jenkins+webhooks-多分支参数化构建-

Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing

波浪动画彩色五角星loader加载js特效
![leetcode:241. Design priority for operation expression [DFS + Eval]](/img/d0/8dedeba7ecedccd25e0e3e96ff3362.png)
leetcode:241. Design priority for operation expression [DFS + Eval]
![[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world](/img/41/76687ea13e1722654b235f2cfa66ce.png)
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world

一款Flutter版的记事本

ZABBIX 6.0 source code installation and ha configuration
随机推荐
SSO and JWT good article sorting
Yarn重启applications记录恢复
Nexus builds NPM dependent private database
Apache-Atlas-2.2.0 独立编译部署
There are risks in trading
PG basics -- Logical Structure Management (trigger)
nexus搭建npm依赖私库
Fundamentals of number theory and its code implementation
Google Earth Engine(GEE)——全球人类居住区网格数据 1975-1990-2000-2014 (P2016)
Operator-1初识Operator
题目 2612: 蓝桥杯2021年第十二届省赛真题-最少砝码(枚举找规律+递推)
高薪程序员&面试题精讲系列118之Session共享有哪些方案?
啟動solr報錯The stack size specified is too small,Specify at least 328k
基于开源流批一体数据同步引擎 ChunJun 数据还原 —DDL 解析模块的实战分享
How to count the status of network sockets?
Development trend and market demand analysis report of China's high purity copper industry Ⓕ 2022 ~ 2028
Simple Fibonacci (recursive)
leetcode 322. Coin Change 零钱兑换(中等)
mysql统计账单信息(下):数据导入及查询
快速整明白Redis中的压缩列表到底是个啥