Store model data into Flutter Secure Storage

Viewed 2136

How do we store model data to flutter secure storage... or does it supports it?

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...

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...

if it is possible then please share the sample code....

2 Answers

to save the object:

  1. convert your object to map with toMap() method
  2. serialize your map to string with serialize(...) method
  3. save the string into secure storage

for restoring your object:

  1. deserialize secure storage string to a map with deserialize(...) method
  2. use fromJson() method to get your 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));

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.

// 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.

Sorry for the late reply :P.

Related