从 rest API 为 Category 创建一个 ListView,而不在 Flutter 中重复
Make a ListView from rest API for Category only without duplication in 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 数据中将公共类别放入 ListView。
有Apple&Microsoft是这6个数据中共同的类别
它是自动完成的。
你能给出解决方案吗?
List getCategory(List data) {
List list = [];
for (var a in data)
if (!list.contains(a["category"]))
list.add(a["category"]);
return list;
}
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());
}
[
{
"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 数据中将公共类别放入 ListView。
有Apple&Microsoft是这6个数据中共同的类别
它是自动完成的。
你能给出解决方案吗?
List getCategory(List data) {
List list = [];
for (var a in data)
if (!list.contains(a["category"]))
list.add(a["category"]);
return list;
}
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());
}