The method 'setStringList' was called on null. when saving using Shared preferences - Flutter

0

I am trying to save a list called transactions inside my provider but I am getting

Receiver: null
Tried calling: setStringList("list", Instance(length:1) of '_GrowableList')

when I try to save

and:

The method 'getStringList' was called on null.
Receiver: null
Tried calling: getStringList("list")

when tying to load.

this is my code :

class Trans extends StatelessWidget with ChangeNotifier {
  SharedPreferences sharedPreferences;

  final text_color = const Color(0xffFFFFFF);

  List <Trans> transactions = [
  ];

  @override
  void initState() {
    initSharedPreferences();
    initState();
  }
  initSharedPreferences() async{
    this.initSharedPreferences();
    sharedPreferences = await SharedPreferences.getInstance();
    loadData();
  }




  bool send;
  Color color;
  double amount;
  Trans({Key key, this.send, this.amount}) : super(key: key);


  Trans.fromMap(Map map)
      : this.send = map['send'],
        this.amount = map['amount'];
  Map toMap() {
    return {
      'send': this.send,
      'amount': this.amount,
    };
  }



  @override


  Widget build(BuildContext context) {...}


  addTrans(){
    transactions.add(Trans(send: this.send, amount: this.amount,));
    notifyListeners();
  }

  void saveData(){
    List<String> stringList = transactions.map(
            (item) => json.encode(item.toMap()
        )).toList();
    sharedPreferences.setStringList('list', stringList);
    notifyListeners();
  }

  void loadData() {
    List<String> stringList = sharedPreferences.getStringList('list');
    if(stringList != null){
      transactions = stringList.map(
              (item) => Trans.fromMap(json.decode(item))
      ).toList();
  
    notifyListeners();
  }
  void clearData() async{
    transactions.clear();
    sharedPreferences.clear();
    saveData();
    notifyListeners();
  }
}

flutter
dart
sharedpreferences
asked on Stack Overflow Jan 6, 2021 by anan saadi

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0