Conner
Conner

Reputation: 1901

Sort Item to front of a list in Dart

I am already sorting my list in dart/flutter alphabetically, with

a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());

However, I would also like to sort one of the items in my list to the front, ignoring the alphabetical sorting. Does anyone know how to do that?

Edit: Here is my Firebase animated list

FirebaseAnimatedList(
      query: query,
      sort: (a, b) {
        return a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());
      },
      padding: EdgeInsets.all(8.0),
      defaultChild: Center(
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation<Color>(appTheme.accentColor),
          strokeWidth: 2.0,
        ),
      ),
      itemBuilder: (BuildContext context, DataSnapshot snapshot,
        Animation<double> animation, int index) {
          return Item(index);
      },
    )

I'm sorting, for example, a list of people's names in this list. But, I want a certain name, "Roger", to always be sorted to the top. How is this possible?

Upvotes: 1

Views: 1951

Answers (1)

Mike Fairhurst
Mike Fairhurst

Reputation: 636

You just want to return -1 & -1 for "Roger" in your sort function:

FirebaseAnimatedList(
  query: query,
  sort: (a, b) {
    if (a == "Roger") return -1;
    if (b == "Roger") return 1;
    return a.value['name'].toString().toLowerCase().compareTo(b.value['name'].toString().toLowerCase());
  },
  padding: EdgeInsets.all(8.0),
  defaultChild: Center(
    child: CircularProgressIndicator(
      valueColor: AlwaysStoppedAnimation<Color>(appTheme.accentColor),
      strokeWidth: 2.0,
    ),
  ),
  itemBuilder: (BuildContext context, DataSnapshot snapshot,
    Animation<double> animation, int index) {
      return Item(index);
  },
)

Upvotes: 2

Related Questions