How to store an Array in flutter storage

Viewed 73

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.

2 Answers

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 :)

Update - Using Provider (https://pub.dev/packages/provider):

You said that you are using provider so I assume you have define it. In your UI you can call Provider.of<yourDataModel>(context) to get the instance of your 'yourDataModel' class. This can be used everywhere you do have a context (most of places but not in initState, for example) to acess or modify your data. Note: it you use it in a function use 'Provider.of(context, listen:false)' because a function doesn't need to rebuild it self when you data changes, only widgets should rebuild.

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