1

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

    });

  }
0

1 Answer 1

5

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Just for safety I would do int.tryParse(value) ?? 0
There's no need for value ?? '0' inside the tryParse
@danypata if you're sure in your data, yes. But if you pass null to int.tryParse it will throw an exception, be careful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.