依赖
sqflite: ^2.3.2 #本地数据储存
获取数据库路径
// 定义一个异步函数来获取数据库路径 Future<String> getDatabasePath(String dbName) async { // 获取应用的文档目录 final directory = await getApplicationDocumentsDirectory(); // 拼接路径 final path = join(directory.path, dbName); return path; }
实体
class TbUserData { late String phone; late String name; late String portraits; late String token; // 构造函数 TbUserData({required this.phone, required this.name, required this.portraits, required this.token}); // 将MyData对象转换为Map Map<String, dynamic> toMap() { return { 'phone': phone, 'name': name, 'portraits': portraits, 'token': token, }; } TbUserData.fromJson(Map<String, dynamic> json) { phone = json['phone']; name = json['name']; portraits = json['portraits']; token = json['token']; } } }
创建
Future<Database> createDatabase() async { // 获取数据库路径 final path = await getDatabasePath('tomato_kid.db'); print("================================================================$path"); // 打开数据库 final database = openDatabase( path, version: 1, // 当数据库第一次被创建时,执行创建表的操作 onCreate: (db, version) { return db.execute( "CREATE TABLE tb_users_login(id INTEGER PRIMARY KEY,phone TEXT,name TEXT, portraits TEXT, token TEXT)", ); }, ); return database; }
添加
Future<void> insertData(TbUserData data, Database db) async { try { // 查询数据库中是否已存在相同电话号码的记录 List<Map<String, dynamic>> existingRecords = await db.query( 'tb_users_login', where: 'phone = ?', whereArgs: [data.phone], ); if (existingRecords.isNotEmpty) { // 如果存在相同电话号码的记录,则替换旧记录 await db.update( 'tb_users_login', data.toMap(), where: 'phone = ?', whereArgs: [data.phone], ); } else { // 如果不存在相同电话号码的记录,则插入新记录 await db.insert( 'tb_users_login', data.toMap(), conflictAlgorithm: ConflictAlgorithm.replace, ); } } catch (e) { // 打印错误信息 print('Failed to insert data: $e'); } }
删除
Future<void> deleteData(String phone, Database db) async { // 调用delete方法删除指定id的数据 await db.delete( 'tb_users_login', // where子句用于指定要删除的数据 where: "phone = ?", whereArgs: [phone], ); }
查看
Future<List<Map<String, dynamic>>> queryAll(Database db) async { // 查询所有数据 return await db.query('tb_users_login'); }
Map转换为MyData对象
Future<List<TbUserData>> getMyDataFromDB(Database db) async { // 获取所有数据 final List<Map<String, dynamic>> maps = await queryAll(db); // 将Map转换为MyData对象 return List.generate(maps.length, (i) { return TbUserData( phone: maps[i]['phone'], name: maps[i]['name'], portraits: maps[i]['portraits'], token: maps[i]['token']); }); }
标签:储存,name,portraits,await,db,sqflite,phone,token,flutter From: https://www.cnblogs.com/xbinbin/p/18085859