List 按值排列的颤振排序列表
如何按列表中的一个值对列表进行排序 这是我的清单的一个例子List 按值排列的颤振排序列表,list,sorting,flutter,List,Sorting,Flutter,如何按列表中的一个值对列表进行排序 这是我的清单的一个例子 List data = [ {'name': 'Example1', 'value1': 10, 'value2': 0}, {'name': 'Example2', 'value1': 0, 'value2': 10}, {'name': 'Example3', 'value1': 15, 'value2': 5}, {'name': 'Example4', 'value1': 22.5, 'val
List data = [
{'name': 'Example1', 'value1': 10, 'value2': 0},
{'name': 'Example2', 'value1': 0, 'value2': 10},
{'name': 'Example3', 'value1': 15, 'value2': 5},
{'name': 'Example4', 'value1': 22.5, 'value2': 10},
];
所以我称之为
Column(
children: data.map((info) {
return Container(
child: SizedBox(
child: Row(
children: [
Text(info['name'],),
Text(info['value1'],),
],
),
),
);
}).toList())
这就是我的列表是如何从上到下列出的
如何按值排序
如果值为0,如何隐藏条目?list.sort使用比较器函数。比较器从列表中获取两个值并进行比较,以查看是否需要交换。根据返回的内容,可以控制列表的排序方式。当返回正值时,交换会发生,否则不会发生 在您的例子中,假设您希望使用value1按递增顺序进行排序。当a>b时,需要告诉比较器返回正值。如果需要降序,请在b>a时返回正值:
List data = [
{'name': 'Example1', 'value1': 15},
{'name': 'Example2', 'value1': 10},
{'name': 'Example3', 'value1': 5},
{'name': 'Example4', 'value1': 0},
];
// sort in place w.r.t. value1
// CompareTo method just returns first value - second value in case of double
// Try returning b['value1'].compareTo(a['value1']) or b['value1'] - a['value1'] and the result should be in descending order w.r.t value1 property.
data.sort((a,b) => a['value1'].compareTo(b['value1'])); // You can also write a['value1'] - b['value1']
print(data.toString());
// To filter (remove all those elements whose value1 is 0)
List filtered = data.where((a) => a['value1'] != 0).toList(); // Where method takes a function which should return true if you want to keep the item in the filtered list.
print(filtered.toString()); // filtered is the new list with all those elements removed.
以下是输出:
[{name: Example4, value1: 0}, {name: Example3, value1: 5}, {name: Example2, value1: 10}, {name: Example1, value1: 15}]
[{name: Example3, value1: 5}, {name: Example2, value1: 10}, {name: Example1, value1: 15}]
更新:
您可以像这样使用过滤器:
Column(
children: data
.where((d) => d['value1'] != 0) // <----- Here :)
.map((info) {
return Container(
child: SizedBox(
child: Row(
children: [
Text(info['name'],),
Text(info['value1'],),
],
),
),
);
}).toList())
这回答了你的问题吗?文档还提供了一个例子:这对我没有任何帮助。我的例子完全不同?在我看来完全一样。如果是不同的,你能解释一下它是如何不同的吗?你能详细说明你的问题以更清楚地解释你想要什么吗?排序后的数据应该是什么样子?链接中有一个完全不同的代码,我需要我的代码示例!排序后,它应该只是一个列表,没有排序,只有值为0的条目应该隐藏