Flutter-数据持久化(shared_preferences、sqflite)
shared_preferences
示例
static Future<void> setToken(String token) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString(TOKEN, token); }
static Future<String?> getToken() async { SharedPreferences prefs = await SharedPreferences.getInstance(); if (await prefs.containsKey(TOKEN)) { var json = await prefs.getString(TOKEN); return json; } else { return null; } }
String? toeken = await DTWRoleManager.getToken();
相关方法
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(key, value)
prefs.setBool(key, value)
prefs.setDouble(key, value)
prefs.setInt(key, value)
prefs.setStringList(key, value)
prefs.remove(key)
prefs.clear()
sqflite
打开数据库(可同时新建或更新表)
DTWDBHandle.internal(); //数据库句柄 static Database? _database; Future<Database?> get database async { if (_database == null) { var databasesPath = await getDatabasesPath(); String path = join(databasesPath, DB_NAME_DTW); _database = await openDatabase(path, version: DB_VERSION, onCreate: _onCreate); } print(_database!.path.toString()); return _database; } //创建表 void _onCreate(Database db, int version) async { final sql = ''' create table if not exists $DB_TABLE_SET ( account text, pid text '''; var batch = db.batch(); batch.execute(sql); await batch.commit(); } //打开 Future<Database?> open() async { return await database; }
插入
Database? db = await DTWDBHandle.internal().open(); await db!.insert(DB_TABLE_SET, setData.toJson()); await db.batch().commit();
修改
Database? db = await DTWDBHandle.internal().open(); String sqlWhere = ''' account='${setData.account}' and pid='${setData.pid}' '''; db!.update(DB_TABLE_SET, setData.toJson(), where: sqlWhere); await db.batch().commit();
删除
Database? db = await DTWDBHandle.internal().open(); String sql = ''' delete from $DB_TABLE_SET where account='${setData.account}' and pid='${setData.pid}' '''; db!.rawDelete(sql); await db.batch().commit();
查询
Database? db = await DTWDBHandle.internal().open(); String sql = '''select * from $DB_TABLE_SET'''; List<Map<String, dynamic>> maps = await db!.rawQuery(sql);