flutter - 仅从类别的其余 API 制作 ListView 而不会在 Flutter 中重复
问题描述
[
{
"category": "Apple",
"name": "Macbook Air"
}, {
"category": "Apple",
"name": "Macbook Pro"
}, {
"category": "Microsoft",
"name": "Surface"
}, {
"category": "Apple",
"name": "iPad"
}, {
"category": "Microsoft",
"name": "Windows"
}, {
"category": "Apple",
"name": "Siri"
}, {
"category": "Microsoft",
"name": "Office"
}
]
我需要从上面示例的 Rest API 数据中将 common 类别转换为 ListView。
苹果和微软是这六个数据中常见的类别。
它是自动完成的。
你能给出一个解决方案吗?
解决方案
import 'dart:convert';
import 'dart:math';
const source = '''
{
"data": [
{ "category": "Apple", "name": "Macbook Air" },
{ "category": "Apple", "name": "Macbook Pro" },
{ "category": "Microsoft", "name": "Surface" },
{ "category": "Apple", "name": "iPad" },
{ "category": "Microsoft", "name": "Windows" },
{ "category": "Apple", "name": "Siri" },
{ "category": "Microsoft", "name": "Office" }
]
}
''';
main(List<String> args) {
final List data = jsonDecode(source)['data'];
var mode = Map<String, int>();
data.map<String>((e) => (e as Map)['category']).forEach((k) => mode[k] = (mode[k] ?? 0) + 1);
var maxVal = mode.values.toList().reduce(max);
var category = List<String>();
mode.forEach((k, v) => v==maxVal ? category.add(k) : null);
print(category.toString());
}