将模型数据存储到Flutter安全存储中

fcy6dtqo  于 2023-02-09  发布在  Flutter
关注(0)|答案(3)|浏览(214)

我们如何存储模型数据以实现安全存储?或者它是否支持安全存储?
我有一个这样的模型......我从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,清除所有的路障,但它仍在开发中...
如果可能,请分享示例代码....

plupiseo

plupiseo1#

要保存对象:
1.用toMap()方法将对象转换为Map
1.使用serialize(...)方法将Map序列化为字符串
1.将字符串保存到安全存储器中
用于还原对象:
1.使用deserialize(...)方法将安全存储字符串反序列化为Map
1.使用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));
}

用法:

final FlutterSecureStorage storage = FlutterSecureStorage();

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

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

2ul0zpep2#

您可以将Model编码为json并保存在Secure Storage中,然后解码json并取回模型。

// 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') ??
          '{}');
}

当然,您需要在模型中实现fromRawJson()toRawJson()
抱歉,回复太晚了。

lxkprmvk

lxkprmvk3#

为此,将模型编码为JSON并存储在安全的存储器中,然后解码JSON以检索模型。

final storage =  FlutterSecureStorage(); 
static const String modelData = "modelData";

// Saving model into Storage
static Future<void> setModel(user) async {
  final jsonDataEncoded = jsonEncode(jsonData);
    await storage.write(key: modelData , value: jsonDataEncoded);
}

//call this when you want to store your data to secured storage
 ClassName.setModel(decodedResponse);//decode your json and send it here

//to read data from the local storage || secured storage
static Future<MyModel> getDataFromLocalStorage() async {
    final jsonModel = await storage.read(key: modelData);
    final jsonData = jsonDecode(jsonModel.toString());
    final items = List.from(jsonData);
    dataList = items.map((e) => MyModel.fromJson(e)).toList();
    return dataList;
  }

相关问题