FloatingRock
FloatingRock

Reputation: 7065

List.sort returns null

I have the following method that retrieves a list of Budgets 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:

How do I fix this?

Upvotes: 1

Views: 291

Answers (2)

jamesdlin
jamesdlin

Reputation: 90125

List.sort mutates the existing List. It does not return a new List.

Upvotes: 1

julemand101
julemand101

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

Related Questions