'flutter how to save and get a list using shared preferences
so ive been trying to set and get a list with shared preferences, but i'm having a problem with retrieving it
import 'package:justatest/model/arguments.dart';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class transactionsAdd extends ChangeNotifier {
List<Addtx> _addtx = [];
List<Addtx> get getAddtx {
return _addtx;
}
void addTrx(var balance, String note, String category, bool plusorminus,
DateTime selectedDate) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
Addtx tdl = new Addtx(note, balance, category, plusorminus, selectedDate);
_addtx.insert(0, tdl);
prefs.setStringList("title1", [_addtx.toString()]);
notifyListeners();
}
loadC2() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_addtx = prefs.getStringList('title1')?? [] ;
notifyListeners();
}
}
`
The problem is with
_addtx = prefs.getStringList('title1')?? [] ;
A value of type 'List' can't be assigned to a variable of type 'List'. Try changing the type of the variable, or casting the right-hand type to 'List'.dartinvalid_assignment
Solution 1:[1]
Although the message is confusing it has sense if you realize that your list _addtx is only for Addtx objects, meanwhile sharedpreferences getStringList is of strings. So you can“t assign a List to a List. You should do something like this:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carlos Sandoval |
