我有以下用dart解码的json:
[{"page":1, "items": [1, 2]}, {"page":2, "items": [3, 4]}]
我想将其展平为一个项目列表:[1, 2, 3, 4]
。我尝试的第一种幼稚方式是:
final x = items.expand((p) => p['items']);
但是它给了我这个错误:
Uncaught exception:
TypeError: Closure 'main_closure': type '(dynamic) => dynamic' is not a subtype of type '(dynamic) => Iterable<dynamic>'
所以我认为问题是p['items']
未被识别为Iterable,然后我尝试了其他方法,但没有用:
final x = items.expand((p) => p['items'] as List<int>);
// CastError: Instance of 'JSArray': type 'JSArray' is not a subtype of type 'List<int>'
final x = items.expand((p) => p['items'].map((i) => i as int);
// TypeError: Closure 'main_closure': type '(dynamic) => dynamic' is not a subtype of type '(dynamic) => Iterable<dynamic>'
以下是代码,也位于dartPad中,用于在线运行:
import 'dart:convert';
void main() {
const jsonString = '[{"page":1, "items": [1, 2]}, {"page":2, "items": [3, 4]}]';
final items = json.decode(jsonString);
//final x = items.expand((p) => p['items']);
//final x = items.expand((p) => p['items'].map((i) => i as int);
print(x);
// When the list is not dynamic, it works
const foo = [{"page":1, "items": [11, 22]}, {"page":2, "items": [33, 44]}];
final y = foo.expand((p) => p['items']);
print(y); // => [1, 2, 3, 4];
// Example from dart's website
const pairs = [[1, 2], [3, 4]];
final flattened = pairs.expand((pair) => pair).toList();
print(flattened); // => [1, 2, 3, 4];
}
当列表是动态的时,该如何使用? json看起来很简单,可以使用json.decode
来完成,而不是像build_value这样的东西来做到这一点。
答案 0 :(得分:2)
只需将解码后的对象投射到List
const jsonString = '[{"page":1, "items": [1, 2]}, {"page":2, "items": [3, 4]}]';
final items = json.decode(jsonString) as List;
final x = items.expand((p) => p['items']);
print(x);
或使用固定的List
类型:
final List items = json.decode(jsonString);