Skip to content

Instantly share code, notes, and snippets.

@davidmartos96
Created January 22, 2021 11:06
Show Gist options
  • Save davidmartos96/559a246bb4a57c24ab071e6b2cc20b32 to your computer and use it in GitHub Desktop.
Save davidmartos96/559a246bb4a57c24ab071e6b2cc20b32 to your computer and use it in GitHub Desktop.
Map as a List helper to make building nested lists in Flutter easier.
import 'package:flutter/material.dart';
class FlatMapItem<MapKey, MapValue> {
MapKey key;
MapValue value;
int index;
FlatMapItem.value(this.value, {@required this.index}) : assert(value != null);
FlatMapItem.key(this.key, {@required this.index}) : assert(key != null);
bool get isKey => key != null;
}
class FlatMap<Key, Value> {
final List<FlatMapItem<Key, Value>> items = [];
final Map<Key, Iterable<Value>> rawMap;
FlatMap(this.rawMap) {
_flattenMapInList(rawMap, items);
}
FlatMap.empty() : rawMap = {};
void _flattenMapInList<Key, Value>(
Map<Key, Iterable<Value>> map,
List<FlatMapItem<Key, Value>> outList
) {
int keyIndex = 0;
int valueIndex = 0;
for (var entry in map.entries) {
outList.add(FlatMapItem.key(entry.key, index: keyIndex));
keyIndex++;
for (var listItem in entry.value) {
outList.add(FlatMapItem.value(listItem, index: valueIndex));
valueIndex++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment