Skip to content

Instantly share code, notes, and snippets.

@lukepighetti
Last active June 25, 2022 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukepighetti/55b1be6c3cda8e689ef0b6126032da64 to your computer and use it in GitHub Desktop.
Save lukepighetti/55b1be6c3cda8e689ef0b6126032da64 to your computer and use it in GitHub Desktop.
Control flow collections example https://dartpad.dev/55b1be6c3cda8e689ef0b6126032da64
/// An example of operations you can do with control flow collections.
///
/// They make it very easy to do map, filter, and spread operations, all
/// while retaining the base class of [List<T>], [Set<T>], and [Map<K,V>]
void main() {
final source = [1, 2, 3, null, 4, 5, null];
/// List control flow, map & filter
final myList = [
for (var number in source)
if (number != null)
if (number.isEven)
'$number is even'
else if (number == 5)
'$number is five'
else
'$number is odd',
/// You can also spread the collection
if (source.length.isOdd) ...['spread foo', 'spread bar']
];
print(myList);
/// Set control flow, map & filter
final mySet = {
for (var number in source)
if (number != null)
if (number.isEven)
'$number is even'
else if (number == 5)
'$number is five'
else
'$number is odd',
/// You can also spread the collection
if (source.length.isOdd) ...{'spread foo', 'spread bar'}
};
print(mySet);
/// Map control flow, map & filter
final myMap = {
for (var number in source)
if (number != null)
if (number.isEven)
number: 'even'
else if (number == 5)
number: 'five'
else
number: 'odd',
/// You can also spread the collection
if (source.length.isOdd) ...{-1: 'spread foo', -2: 'spread bar'}
};
print(myMap);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment