flutterdartflutter-search-delegate

how to sort in flutter search delegate?


I have a delegate file for search into some items , its working and shows the item but when I type something in the search field the items remain the same , my problem is I don't know how to add a sorting option to this , this is some part of the code below that shows the items in a Card , any idea please ?

  @override
  Widget buildResults(BuildContext context) {
  BlocBuilder<CardListBloc, CardState>(
    builder: (context, state) {
      itemBuilder: (context, index) {
              return Card(
                elevation: 4,
                shape: cardRadius(4),
                margin: EdgeInsets.only(left: 12, right: 12, top: index == 0 ? 12 : 
                0),
                child: Container(
                  width: double.infinity,
                  child: ListTile(
                    title: Text(state.mTicket.cards[index].name),
                    subtitle: Text(Jiffy(state.mTicket.cards[index].createdOn).MEd),
                  }

Solution

  • You could modify your code to sort the items alphabetically by name:

    @override
    Widget buildResults(BuildContext context) {
      BlocBuilder<CardListBloc, CardState>(
        builder: (context, state) {
          List<CardItem> items = state.mTicket.cards.where((card) =>
            card.name.toLowerCase().contains(query.toLowerCase())).toList();
          items.sort((a, b) => a.name.compareTo(b.name)); // sort by name
          
          return ListView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              return Card(
                elevation: 4,
                shape: cardRadius(4),
                margin: EdgeInsets.only(left: 12, right: 12, top: index == 0 ? 12 : 0),
                child: Container(
                  width: double.infinity,
                  child: ListTile(
                    title: Text(items[index].name),
                    subtitle: Text(Jiffy(items[index].createdOn).MEd),
                  ),
                ),
              );
            },
          );
        }
      );
    }
    

    This modified implementation uses the sort() method to sort the items list by name before displaying them in the ListView. You can modify the sorting function to sort the items based on different criteria, such as date or popularity, depending on your needs.