Skip to content

Instantly share code, notes, and snippets.

@charlieman
Created July 16, 2019 05:29
Show Gist options
  • Save charlieman/9f654528d2f8d05abc14a7bd9282bda3 to your computer and use it in GitHub Desktop.
Save charlieman/9f654528d2f8d05abc14a7bd9282bda3 to your computer and use it in GitHub Desktop.
import 'dart:convert';
void main() {
// Json obtained through some api:
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'] as List<int>);
//final x = items.expand((p) => p['items'].map((i) => i as int));
//final x = items.map((p) => p['items'] as List).toList().expand((i) => i).toList();
print(x);
// When the list is not dynamic, it works:
const foo = [{"page":1, "items": [1, 2]}, {"page":2, "items": [3, 4]}];
final y = foo.expand((p) => p['items']).toList();
//final y = foo.map((p) => p['items']).toList().expand((i) => i).toList();
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];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment