Reputation: 5012
I use texfield to add number. After this I save in sharepreference the value in List
I search to make an addition of each value saved in this List
I tried this, but it doesn't works.
load_list()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
stringList = prefs.getStringList("list");
sum = stringList.reduce((value, element) => value + element);
});
}
Upvotes: 1
Views: 1082
Reputation: 9903
reduce returns the same type as the type in the collection, so you should use fold instead.
final List<String> stringList = prefs.getStringList("list") ?? [];
final int sum = stringList.fold<int>(0, (prev, value) => prev + int.parse(value));
To make it completely null-safe:
final int sum = stringList.fold<int>(0, (prev, value) => prev + (int.tryParse(value ?? '0') ?? 0));
Upvotes: 5