Storage



Introduction

In Nylo you can save data to the users device using the NyStorage class.

This uses the flutter_secure_storage package to save and retrieve data.


Store values

To store values, you can use the below helper.

import 'package:nylo_framework/helpers/helper.dart';
...

NyStorage.store("com.company.myapp.coins", "10");


Retrieve values

To retrieve values, you can use the below helper.

import 'package:nylo_framework/helpers/helper.dart';
...

String coins = await NyStorage.read("com.company.myapp.coins"); // 10


Introduction to storable models

Storable models are useful for storing small sized data to the users devices. It can be helpful way to store the users progress in a game, coins or even their api token.

Here's a model that extends the Storable class.

class User extends Storable {
  String token;
  String username;
  String favouriteCity; 

  User({this.token, this.username, this.favouriteCity});

  @override
  toStorage() => {
      "token": this.token, 
      "username": this.username, 
      "favourite_city": this.favouriteCity
    };

  @override
  fromStorage(dynamic data) {
    this.token = data['token'];
    this.username = data['username'];
    this.favouriteCity = data['favourite_city'];
  }
}

After extending the Storable class, you then need to override the toStorage() and fromStorage methods.

  • toStorage() - Creates the payload to be stored.

  • fromStorage(dynamic data) - This will create the model from the data payload, the keys should match the toStorage() method.


Saving a Storable model

To save a Storable model, you can use the below helper.

import 'package:nylo_framework/helpers/helper.dart';
...

String key = "com.company.myapp.auth_user";

User user = new User();
user.username = "Anthony";

user.save(key);

// or 

NyStorage.store(key, user);


Retrieve a Storable model

To retrieve a Storable model, you can use the below helper.

import 'package:nylo_framework/helpers/helper.dart';
...
String key = "com.company.myapp.auth_user";

User user = await NyStorage.read(key, model: new User());
print(user.username); // Anthony