Store data model into Flutter Secure Storage

7.2k Views Asked by At

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 vice 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 also Author is working on an alternative to hive due to two major blocks... the new database called Isar which clears all roadblock but it is still in development...

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

3

There are 3 best solutions below

4
On

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) =>
    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));
0
On

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.

0
On

To do this, encode your model into JSON and store it in secure storage. Later, decode the JSON to retrieve the model.

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