将数据模型存储到 Flutter Secure Storage 中

2024-04-28

我们如何将模型数据存储到 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;
}

当然,我知道我们可以像下面这样读取和写入数据...我只是检查是否有一种方法可以直接从模型写入数据...

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

我看到 hive 开箱即用地支持此功能,但我意识到初始化也只需要很少的时间(2-3 秒),作者正在研究 hive 的替代方案,因为有两个主要块......新数据库称为Isar https://github.com/isar/isar这清除了所有障碍,但仍在开发中......

如果可能的话请分享示例代码...


保存对象:

  1. 将您的对象转换为地图toMap() method
  2. 将您的地图序列化为字符串serialize(...) method
  3. 将字符串保存到安全存储中

用于恢复您的对象:

  1. 将安全存储字符串反序列化为映射deserialize(...) method
  2. use 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));
}

Usage:

final FlutterSecureStorage storage = FlutterSecureStorage();

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

MyUserModel model = MyUserModel.deserialize(await storage.read(key: key));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将数据模型存储到 Flutter Secure Storage 中 的相关文章

随机推荐