Sort list of objects in a stream and return the sorted list as a stream in flutter

Issue

I have list of users. I need to sort this user data based on gender. gender = { 0: ‘male’, 1: ‘female’, 2: ‘others’}.

I want the date to be ordered in such a way that females are listed first, followed by males and then others i.e, {1, 0, 2}.

class User {
  String id;
  String name;
  int gender;

  User({
    this.id,
    this.name,
    this.gender,
  })

  factory users.fromMap(Map<String, dynamic> data, String documentId) {
    if (data == null) {
      return null;
    }

    return User(
      ...
    );
  }

  Map<String, dynamic> toMap() => <String, dynamic>{
    ...
  }
}

Is there anyway to sort the data based on the above condition and return a stream again?

The stream I receive from database is below:

Stream<List<User>> users =
        database.usersStream();

Now, is users object sortable using rxdart or is there any other way?
and how to do that?

Solution

You can sort the list in your usersStream method.

Try the following steps.

1. Implement Comparable in your User class and override the compareTo method.

class User implements Comparable<User> {
  String id;
  String name;
  int gender;

  User({
    this.id,
    this.name,
    this.gender,
  });

  @override
  String toString() {
    return "User(id: $id, gender: $gender)";
  }

  @override
  int compareTo(User other) {
    if (gender == 1) {
      return -1;
    }
    if (other.gender == 1) {
      return 1;
    }
    return gender.compareTo(other.gender);
  }
}

2. Sort the list in usersStream using the compareTo method.

Stream<List<User>> usersStream() async* {

  //This is dummy data for users.
  List<User> users = List.generate(20, (index) {
    Random random = Random();
    int gender = random.nextInt(3);
    return User(id: index.toString(), gender: gender, name: "User $index");
  });

  //Sorting the list.
  users.sort((User a, User b) {
    return a.compareTo(b);
  });

  yield users;
}

Answered By – Josteve

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *