Reputation: 7065
I have the following method that retrieves a list of Budget
s from an API and sorts them prior to processing:
response['budgets']
.map((budget) => Budget.fromJson(budget))
.toList()
.sort((a, b) => budgetComparator(a, b))
.forEach((budget) => addBudget(budget));
The budgetComparator
is a method that returns an int
between -1 and 1:
int budgetComparator(Budget a, Budget b) {
String purposeA = purposeById(a.purposeId).name,
purposeB = purposeById(b.purposeId).name;
return purposeA.compareTo(purposeB);
}
When I run the above, I get the error message:
NoSuchMethodError: The method 'forEach' was called on null
When debugging, I was able to observe that:
sort()
method was indeed returning null
toList()
method returns a list of 8 Budget
itemsbudgetComparator
ALWAYS returns an integer that is either -1, 0 or 1How do I fix this?
Upvotes: 1
Views: 291
Reputation: 90125
List.sort
mutates the existing List
. It does not return a new List
.
Upvotes: 1
Reputation: 31269
Yes, the sort
method are indeed returning null:
https://api.dart.dev/stable/2.7.2/dart-core/List/sort.html
What you can do if you still want to make a one liner is make use of the cascade notation: https://dart.dev/guides/language/language-tour#cascade-notation-
response['budgets'].map((budget) => Budget.fromJson(budget)).toList()
..sort((a, b) => budgetComparator(a, b))
..forEach((budget) => addBudget(budget));
So instead of running forEach
on the result of sort
we will instead here run forEach
on the list from toList
after sort
has been called on the list.
Upvotes: 3