Skip to content

Instantly share code, notes, and snippets.

@hotdang-ca
Created May 14, 2024 20:18
Show Gist options
  • Save hotdang-ca/4ca2044d217f5bb70932e371137cdac7 to your computer and use it in GitHub Desktop.
Save hotdang-ca/4ca2044d217f5bb70932e371137cdac7 to your computer and use it in GitHub Desktop.
Sets in Dart
void main() {
Set<String> smartTags = {};
final List<Product> productsToPullTagsFrom = [
Product(productName: 'Product A', bvTags: ['tag 1']),
Product(productName: 'Product B', bvTags: ['tag 2', 'tag 3']),
Product(productName: 'Product C', bvTags: ['tag 1', 'tag 3']),
Product(productName: 'Product D'), // no tags, and in fact, tags are null
Product(productName: 'Product E', bvTags: []),
Product(productName: 'Product F', bvTags: ['tag 1', 'tag 2', 'tag 3', 'tag 4']),
Product(productName: 'Product G', bvTags: ['tag 1', 'tag 1', 'tag 1', 'tag 1', 'tag 1', 'tag 1', 'tag 1'])
];
productsToPullTagsFrom.forEach((p) {
if (p.bvTags != null) {
if (p.bvTags!.isNotEmpty) {
smartTags.addAll(p.bvTags!); // avoids an inner-loop required. addAll will individually add the elements of one list to another.
}
}
});
// out of 6 products, there are only 4 unique tags.
// Try changing this to see if you can avoid the error
final int expectedLength = 16;
try {
assert(smartTags.length == expectedLength);
} on AssertionError {
print('***\nIf you see this message, we dont have the right number of tags in our Set.\n\nLength of smart tags is ${smartTags.length}, but we asserted it would be $expectedLength\n***');
} catch (e) {
// some other sort of error
print(e);
}
print('Smart tags in Set<String> smartTags is: [${smartTags.join(', ')}]');
}
class Product {
final String productName;
final List<String>? bvTags;
Product({required this.productName, this.bvTags});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment