Is there a way that we could save a map object into shared preferences so that we can fetch the data from shared preferences rather than listening to the database all the time. actually i want to reduce the amount of data downloaded from firebase. so i am thinking of a solution to have a listener for shared prefs and read the data from shared prefs.
But i dont see a way of achieving this in flutter or dart.
Please can someone help me to achieve this if there is a workaround.
Many Thanks, Mahi
There is no option to save the map inside shared preference directly. You have to convert the map into a string using json. encode() method. When you get the string back you have to decode it using json.
First, in order to use the SharedPreferences , we have to use Flutter's plugin for it. To do so, make sure dependencies in your pubspec. yaml file looks similar to this: To save something in SharedPreferences , we must provide a value that we want to save and a key that identifies it.
If you convert it to a string, you can store it
import 'dart:convert'; ... var s = json.encode(myMap); // or var s = jsonEncode(myMap);
json.decode(...)
/jsonDecode(...)
makes a map from a string when you load it.
Might be easier with this package: https://pub.dartlang.org/packages/pref_dessert
Look at the example:
import 'package:pref_dessert/pref_dessert.dart'; /// Person class that you want to serialize: class Person { String name; int age; Person(this.name, this.age); } /// PersonDesSer which extends DesSer<T> and implements two methods which serialize this objects using CSV format: class PersonDesSer extends DesSer<Person>{ @override Person deserialize(String s) { var split = s.split(","); return new Person(split[0], int.parse(split[1])); } @override String serialize(Person t) { return "${t.name},${t.age}"; } } void main() { var repo = new FuturePreferencesRepository<Person>(new PersonDesSer()); repo.save(new Person("Foo", 42)); repo.save(new Person("Bar", 1)); var list = repo.findAll(); }
Package is still under development so it might change, but any improvements and ideas are welcomed! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With