Skip to main content

avoid-not-assignable-collection-types

effort: 3m
configurable
pro+

Warns when a collection with non-nullable elements is passed to a parameter that accepts a collection with nullable elements and which is mutated within the function/method body.

Adding an element to such a parameter will throw a runtime exception if the element is equal null.

To address this issue, try changing the collection to accept nullable values or make the parameter type to accept only non-nullable elements.

By default triggers on the following methods: add, addAll, addEntries, insert, insertAll, fillRange, putIfAbsent, replaceRange, setAll, setRange, update, updateAll.

⚙️ Config

Set additional-methods (default is empty) to add additional methods to the list of the default methods.

analysis_options.yaml
dcm:
rules:
- avoid-not-assignable-collection-types:
additional-methods:
- customAddMethod

Example

❌ Bad:

void fn() {
final conditionTargets = <String, String>{};
// LINT: Passing a collection with non-nullable elements can lead to a runtime exception if the collection is updated with a null value inside the invocation.
// Try changing the collection to accept nullable values or make the parameter type to accept only non-nullable elements.
_extractConditionTargetsMap(conditionTargets);

final conditionTargets = <String>{};
// LINT: Passing a collection with non-nullable elements can lead to a runtime exception if the collection is updated with a null value inside the invocation.
// Try changing the collection to accept nullable values or make the parameter type to accept only non-nullable elements.
_extractConditionTargets(conditionTargets);
}

void _extractConditionTargetsMap(Map<String?, String?> targets) {
targets['hello'] = null;
}

void _extractConditionTargets(Set<String?> targets) {
targets.add(null);
}

✅ Good:

void fn() {
final conditionTargets = <String, String>{};
_extractConditionTargetsMap(conditionTargets);

final conditionTargets = <String?>{}; // Now nullable
_extractConditionTargets(conditionTargets);

final conditionTargets = <String>{};
_notMutated(conditionTargets); // Not mutated within the body of the function
}

// Now accepts only non-nullable values
void _extractConditionTargetsMap(Map<String, String> targets) {
targets['hello'] = 'there';
}

void _extractConditionTargets(Set<String?> targets) {
targets.add(null);
}

void _notMutated(Set<String?> target) {
if (targets.contains('value')) {
...
}
}

Additional Resources