【问题标题】:Flutter/Dart Sort List only where bool true isFlutter/Dart 排序列表仅在 bool true 为
【发布时间】:2022-01-22 19:11:15
【问题描述】:

我想实现只有 bool isActive 为 true 的 Tourneys 才能显示并按照 Toruney 日期最接近当前日期的顺序排序。

List<NewPokerTourneyClass> avail 我得到三个锦标赛,这是正确的,但是当我想对List<NewPokerTourneyClass> avail 进行排序时,锦标赛没有得到排序。使用注释掉的排序功能,它可以对所有锦标赛进行排序,这不是我想要的。

ListView.builder(
          scrollDirection: Axis.vertical,
          itemCount: _pokerTourneyProvider.tourney!
              .where((element) => element.isActive == true)
              .length,
          itemBuilder: (context, index) {
            List<NewPokerTourneyClass> avail = _pokerTourneyProvider.tourney!
                .where((element) => element.isActive == true)
                .toList();
            avail.sort((a, b) {
              final one = a.dateTime?.millisecondsSinceEpoch;
              final two = b.dateTime?.millisecondsSinceEpoch;
              return one!.compareTo(two!);
            });

            // _pokerTourneyProvider.tourney!.sort((one, two) {
            //   final oneMilli = one.dateTime?.millisecondsSinceEpoch;
            //   final twoMilli = two.dateTime?.millisecondsSinceEpoch;
            //   return oneMilli!.compareTo(twoMilli!);
            // });

【问题讨论】:

  • 尝试将List&lt;NewPokerTourneyClass&gt; avail = _pokerTourneyProvider.tourney! .where((element) =&gt; element.isActive == true) .toList(); avail.sort((a, b) { final one = a.dateTime?.millisecondsSinceEpoch; final two = b.dateTime?.millisecondsSinceEpoch; return one!.compareTo(two!); });移动到itembuilder之外,并检查它是否没有再次排序,例如处于初始化状态或其他状态

标签: flutter sorting dart


【解决方案1】:

只需分离您的排序函数并更新 _pokerTourneyProvider.tourney 列表。

List<NewPokerTourneyClass> getTurneySortedList(bool order) {
List<NewPokerTourneyClass> availList = _pokerTourneyProvider.tourney!
            .where((element) => element.isActive == true)
            .toList();;

order 是一个布尔类型值。如果升序通过顺序 = true,如果降序通过顺序 = false。

 if (order) {
      availList .sort((a, b) => a.createdAt!.compareTo(b.createdAt!));
    } else {
      availList .sort((a, b) => b.createdAt!.compareTo(a.createdAt!));
    }

    return availList ;
  }

【讨论】:

  • 首先,感谢您的回答,但遗憾的是,将 getTurneySortedList(true) 添加到 itemBuilder 并没有像 _pokerTourneyProvider.tourney!.sort((one, two) { final oneMilli = one.dateTime?.millisecondsSinceEpoch; final twoMilli = two.dateTime?.millisecondsSinceEpoch; return oneMilli!.compareTo(twoMilli!); }); 那样对列表进行排序,甚至将您的代码更改为毫秒,因为Epoch 没有起到作用
猜你喜欢
  • 2023-01-03
  • 2022-12-07
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 1970-01-01
  • 2020-08-28
  • 2020-12-03
  • 2019-10-26
相关资源
最近更新 更多