Bloc: [Question] How to correctly sort a list

Created on 30 Jul 2020  路  3Comments  路  Source: felangel/bloc

Describe the bug
I can't seem to emit more than one state when sorting a list more than once.

To Reproduce
Steps to reproduce the behavior:

  1. Create a bloc with a list:
final _users = [
  User(firstName: "Zz", lastName: "Aa"),
  User(firstName: "Aa", lastName: "Zz"),
];
  1. Emit an event to sort the list by last name
  2. List changes
  3. Emit an event to sort the list by first name
  4. No state emitted

Workaround
I had to create different states for this to work correctly

BlocState.loaded(users: _users),
BlocState.filteredByFirstName(users: _users),
BlocState.filteredByLastName(users: _users),

Since this is very verbose, I feel like it is probably the wrong approach.

Expected behavior
A new state to be emitted when the list changes more than once.

BlocState.loaded(users: _users), // sorted by first name
BlocState.loaded(users: _users), // sorted by last name

Additional context
I assume the new state is not being emitted because the state is the same, but the list is different? Not sure why it would only emit once.

question

Most helpful comment

Thanks @RollyPeres it worked

Solution:

var sorted = List<User>.from(_friends)
      ..sort((a, b) => a.firstName.compareTo(b.firstName));

yield FriendsListState.loaded(friends: sorted);

All 3 comments

Hi @VictorUvarov 馃憢

You're probably applying the sorting directly which is modifying the existing list so value equality won't work.
Instead do yield List.from(_users)..sort(...);

I am doing it directly thanks for the advice I'll try it out 馃檪

Thanks @RollyPeres it worked

Solution:

var sorted = List<User>.from(_friends)
      ..sort((a, b) => a.firstName.compareTo(b.firstName));

yield FriendsListState.loaded(friends: sorted);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

1AlexFix1 picture 1AlexFix1  路  3Comments

wheel1992 picture wheel1992  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

hivesey picture hivesey  路  3Comments

Reidond picture Reidond  路  3Comments