Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

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

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();
  }
}

question from:https://stackoverflow.com/questions/65600716/the-method-setstringlist-was-called-on-null-when-saving-using-shared-preferen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...