Pra*_*een 4 serialization flutter flutter-secure-storage
我们如何将模型数据存储到 flutter 安全存储中……或者它支持吗?
我有一个这样的模型...我将数据从我的 API 加载到这个模型...一旦我有了数据,我想将其保存到 flutter 安全存储中,反之亦然(将整个数据从 flutter 安全存储加载到模型中) ...
class MyUserModel {
MyUserModel({
this.authKey,
this.city,
this.contact,
this.email,
this.isContact,
this.userId,
});
String authKey;
String city;
String contact;
dynamic email;
bool isContact;
int userId;
}
Run Code Online (Sandbox Code Playgroud)
当然,我知道我们可以像下面这样读取和写入数据...我只是检查是否有一种方法可以直接从模型写入数据...
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// Create storage
final storage = new FlutterSecureStorage();
// Read value
String value = await storage.read(key: key);
// Write value
await storage.write(key: key, value: value);
Run Code Online (Sandbox Code Playgroud)
我看到 hive 开箱即用地支持此功能,但我意识到初始化也只需要很少的时间(2-3 秒)作者正在研究 hive 的替代方案,因为有两个主要块......名为Isar的新数据库可以清除所有障碍,但它仍在开发中......
如果可能的话请分享示例代码...
Ham*_*med 15
保存对象:
toMap()
使用方法将您的对象转换为地图serialize(...)
使用方法将映射序列化为字符串- 将字符串保存到安全存储中
用于恢复您的对象:
deserialize(...)
使用方法将安全存储字符串反序列化为映射- 使用
fromJson()
方法来获取你的对象
这样,您将把数据序列化为字符串并保存和检索它们。
class MyUserModel {
String authKey;
String city;
String contact;
dynamic email;
bool isContact;
int userId;
MyUserModel({
required this.authKey,
required this.city,
required this.contact,
required this.email,
required this.isContact,
required this.userId,
});
factory MyUserModel.fromJson(Map<String, dynamic> jsonData) =>
MyUserModel(
authKey: jsonData['auth_key'],
city: jsonData['city'],
contact: jsonData['contact'],
email: jsonData['email'],
isContact: jsonData['is_contact'] == '1',
userId: jsonData['user_id'],
);
}
static Map<String, dynamic> toMap(MyUserModel model) =>
<String, dynamic> {
'auth_key': model.authKey,
'city': model.city,
'contact': model.contact,
'email': model.email,
'is_contact': model.isContact ? '1' : '0',
'user_id': model.userId,
};
static String serialize(MyUserModel model) =>
json.encode(MyUserModel.toMap(model));
static MyUserModel deserialize(String json) =>
MyUserModel.fromJson(jsonDecode(json));
}
Run Code Online (Sandbox Code Playgroud)
用法:
final FlutterSecureStorage storage = FlutterSecureStorage();
await storage.write(key: key, value: MyUserModel.serialize(model));
MyUserModel model = MyUserModel.deserialize(await storage.read(key: key));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6965 次 |
最近记录: |