Home > Mobile >  How to store an Array in flutter storage
How to store an Array in flutter storage

Time:08-22

I some set of list coming from a server, which I would be using in multiple pages in my app. So I'm thinking of storing it in flutter storage or something to avoid loading the same content everytime in different pages. So the issue is storing the array to flutter storage, which wouldn't work as it only stores string.

I dont know if there is any other approach to this or how can I convert to string and save, and how can I delete this item and add some other item as well.

CodePudding user response:

Your question is misleading. What do you mean by Flutter Storage?

To save data between screens we use a State Management approach, like Provider, Mobx, Bloc, etc. or even a simple statefull widget if that's enought for the use case.

You can use the local app storage (take a look at https://pub.dev/packages/shared_preferences).

Your problem can be easily answer but you need to clarify your question. Most likelly what your are looking for is to create a simple class that stores the data inside a provider/mobx (you can pick other) and be access in your whole app :)

CodePudding user response:

You can store the array in a map as a JSON string in the flutter storage. You can add and delete the item by using the map methods.

import 'dart:convert';

final storage = new FlutterSecureStorage();

Map<String, List<int>> map = {
    'key1': [1, 2, 3],
};

final mapEncoded = jsonEncode(map);
await storage.write(key: "mapKey", value: mapEncoded);
print(mapEncoded);
final mapDecoded = jsonDecode(storage.read(key: "mapKey"));
print(mapDecoded);

Output

{"key1":[1,2,3]}
{key1: [1, 2, 3]}
  • Related