简体   繁体   English

将 model 数据存储到 Flutter 安全存储中

[英]Store model data into Flutter Secure Storage

How do we store model data to flutter secure storage... or does it supports it?我们如何将 model 数据存储到 flutter 安全存储......或者它是否支持它?

I have a model like this... I load data from my API to this model... once I have data, I wanted to save it to the flutter secure storage and vise versa(load entire data to model from flutter secure storage)... I have a model like this... I load data from my API to this model... once I have data, I wanted to save it to the flutter secure storage and vise versa(load entire data to model from flutter secure storage) ...

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;
}

Of course, I know we can read and write data like below... I am just checking if there is a way where we can directly write it from the model...当然,我知道我们可以像下面这样读写数据……我只是在检查是否有一种方法可以直接从 model 写入数据……

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);

I saw hive supports this feature out of the box but I realized that it takes little time (2-3 sec) for initialization and also Author is working on an alternative to hive due to two major blocks... the new database called as Isar which clears all road block but it is still in development...我看到 hive 开箱即用地支持此功能,但我意识到初始化需要很少的时间(2-3 秒),而且由于两个主要块,作者正在研究 hive 的替代品......称为Isar的新数据库它清除了所有路障,但仍在开发中...

if it is possible then please share the sample code....如果可能的话,请分享示例代码....

You can do this by encoding your Model into json saving it in Secure Storage and then decode the json and get the model back.您可以通过将 Model 编码为 json 将其保存在Secure Storage中,然后解码 json 并获取 Z20F35E630DAF544DBFACZ35E630DAF544DBFAC88。

// Saving model into Storage
static Future<void> setMyUserModel(MyUserModel user) async {
  await const FlutterSecureStorage().write(
    key: 'user', value: user.toRawJson());
}

// Getting model from storage
static Future<MyUserModel> getMyUserModel() async {
  return MyUserModel.fromRawJson(
      await const FlutterSecureStorage().read(key: 'user') ??
          '{}');
}

And of course you need to implement fromRawJson() and toRawJson() inside your model.当然,您需要在 model 中实现fromRawJson()toRawJson()

Sorry for the late reply:P.抱歉回复晚了:P。

to save the object:保存 object:

  1. convert your object to map with toMap() method使用toMap()方法将您的 object 转换为 map
  2. serialize your map to string with serialize(...) method使用serialize(...)方法将您的 map 序列化为字符串
  3. save the string into secure storage将字符串保存到安全存储中

for restoring your object:用于恢复 object:

  1. deserialize secure storage string to a map with deserialize(...) method使用 deserialize deserialize(...)方法将安全存储字符串反序列化为 map
  2. use fromJson() method to get your object使用fromJson()方法获取您的 object

by that, you will serialize your data into a string and save and retrieve them.这样,您将数据序列化为字符串并保存和检索它们。

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) {
    return 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) => {
        '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(json);
}

Usage:用法:

final FlutterSecureStorage storage = FlutterSecureStorage();

await storage.write(key: key, value: MyUserModel.serialize(model));

MyUserModel model = MyUserModel.deserialize(await storage.read(key: key));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM