我一直在尝试使用flutter编写一个应用程序。该应用程序与所有基本应用程序一样具有登录/注册功能。为此,我使用了一个API链接,得到的响应是JSON格式的。响应包含用户id、姓名、年龄等数据。我想将这些数据存储在设备上的本地数据库中,这样我就可以使用这些数据显示一些信息并登录帐户,而无需用户反复输入详细信息。我一直在尝试各种方法来实现这一点,但无法做到。我遵循了sqflite的官方文档,但未能成功运行它。我真的很期待能得到任何帮助。
提前谢谢。如果你需要任何数据/代码,请告诉我,我会发布同样的数据/代码。
1.在pubspec.yaml 上实现以下依赖项
sqflite: ^2.0.0+3
(dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.3
sqflite: ^2.0.0+3)
2.创建模型类
class Student {
int id;
String name;
Student(this.id, this.name);
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'name': name,
};
return map;
}
Student.fromMap(Map<String, dynamic> map) {
id = map['id'];
name = map['name'];
}
}
3.创建dbhelper类
import 'package:flutter_sqlite_crud/student_model.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class DBHelper {
static Database _db;
Future<Database> get db async {
if (_db != null) {
return _db;
}
_db = await initDatabase();
return _db;
}
initDatabase() async {
io.Directory documentDirectory = await getApplicationDocumentsDirectory();
String path = join(documentDirectory.path, 'student.db');
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}
_onCreate(Database db, int version) async {
await db
.execute('CREATE TABLE student (id INTEGER PRIMARY KEY, name TEXT)');
}
Future<Student> add(Student student) async {
var dbClient = await db;
student.id = await dbClient.insert('student', student.toMap());
return student;
}
Future<List<Student>> getStudents() async {
var dbClient = await db;
List<Map> maps = await dbClient.query('student', columns: ['id', 'name']);
List<Student> students = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i++) {
students.add(Student.fromMap(maps[i]));
}
}
return students;
}
Future<int> delete(int id) async {
var dbClient = await db;
return await dbClient.delete(
'student',
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> update(Student student) async {
var dbClient = await db;
return await dbClient.update(
'student',
student.toMap(),
where: 'id = ?',
whereArgs: [student.id],
);
}
Future close() async {
var dbClient = await db;
dbClient.close();
}
}
4.创建UI设计类。。。。