Can i store a Map inside a Shared Preferences in dart?

前端 未结 3 2016
离开以前
离开以前 2020-12-29 03:56

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 ti

相关标签:
3条回答
  • 2020-12-29 04:20

    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.

    0 讨论(0)
  • 2020-12-29 04:26

    For those who don't like to convert String to JSON or vice versa, personally recommend localstorage, this is the easiest way I had ever found to store any data<T> in Flutter.

    import 'package:localstorage/localstorage.dart';
    
    final LocalStorage store = new LocalStorage('myapp');
    
    ...
    
    setLocalStorage() async {
      await store.ready;       // Make sure store is ready
      store.setItem('myMap', myMapData);
    }
    
    ...
    
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-29 04:32

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

    0 讨论(0)
提交回复
热议问题