Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i store a Map<String, Object> inside a Shared Preferences in dart?

Tags:

flutter

dart

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

like image 591
Mahi Avatar asked Jan 05 '18 15:01

Mahi


People also ask

How do I save maps in shared preferences Flutter?

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.

Can we store object in SharedPreferences Flutter?

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.


2 Answers

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.

like image 144
Günter Zöchbauer Avatar answered Sep 20 '22 17:09

Günter Zöchbauer


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

like image 23
bartektartanus Avatar answered Sep 20 '22 17:09

bartektartanus