如何在Dart中按bool对列表进行排序 [英] How do you sort a list by bool in Dart

查看:53
本文介绍了如何在Dart中按bool对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据 bool 值在dart中对 List 进行排序, compareTo 方法不适用于 bool.我希望 true 值显示在列表的顶部.

How do you sort a List in dart based on a bool value, the compareTo method doesn't work with bool. I want true values to appear at the top of the list.

推荐答案

您可以为 bool 定义自己的比较函数,并将其传递给 sort 方法>列表.

You can define your own compare function for bool and pass it to the sort method of List.

使用 booleans 作为您的 bool List 的示例:

Example with booleans as your bool List:

booleans.sort((a, b) {
  if(b) {
    return 1;
  }
  return -1;
});

此示例告诉 sort 方法,应该将 true 元素排序为高于 false 元素.

This example tells the sort method that true elements should be sorted higher than false elements.

这篇关于如何在Dart中按bool对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆