Dimibe / grouped_list

A Flutter ListView in which items can be grouped into sections.
https://pub.dev/packages/grouped_list
MIT License
395 stars 106 forks source link

Variable to change order #124

Closed GinoChasles closed 9 months ago

GinoChasles commented 2 years ago

Hello,

I'm using SliverGroupedListView and i had a variable for the order. I use radio button to SetState the var to DESC/ASC. If I use groupComparator: (value1, value2) => value2.compareTo(value1) when I change ASC to DESC order the name of groups change but the list of items doesn't reverse. If I use groupComparator: (value1, value2) => _groupComparator(value2, value1) where the function is:

int _groupComparator(String value1, String value2) {
      int result;
        result = value2.compareTo(value1);
      if(taskProvider.taskSort.groupedDirection == GroupedListOrder.DESC) {
        result = value1.compareTo(value2);
      } 
      return result;
    }

This time when I change ASC to DESC the list of items reversed but not groups ^^"

Any idea to resolve this ? x) Thanks for time your consacrete to me.

GinoChasles commented 2 years ago

So I allow myself to copy the sliver_grouped_list.dart and I modify the _sortElements() to solve my problem.

List<T> _sortElements() {
    var elements = widget.elements;
    if (widget.sort && elements.isNotEmpty) {
      elements.sort((e1, e2) {
        var compareResult;
        // compare groups
        if (widget.groupComparator != null) {
          compareResult =
              widget.groupComparator(widget.groupBy(e1), widget.groupBy(e2));
        } else if (widget.groupBy(e1) is Comparable) {
          compareResult = (widget.groupBy(e1) as Comparable)
              .compareTo(widget.groupBy(e2) as Comparable);
        }
        // compare elements inside group
        if ((compareResult == null || compareResult == 0)) {
          if (widget.itemComparator != null) {
            compareResult = widget.itemComparator(e1, e2); 
          } else if (e1 is Comparable) {
            compareResult = e1.compareTo(e2);
          }
        }
//new condition
 else if (widget.groupComparator != null  
            && widget.order == GroupedListOrder.DESC) {
              compareResult = (widget.groupBy(e2) as Comparable)
              .compareTo(widget.groupBy(e1) as Comparable);
        } 
        return compareResult;
      });
// remove this
      // if (widget.order == GroupedListOrder.DESC) {
      //   elements = elements.reversed.toList();
      // } 
    }
    return elements;
  }

and it work like as want :)

Dimibe commented 9 months ago

Info for future readers: Can be solved by using itemComparator and groupComparator.