avoid-not-encodable-in-to-json
preset: recommended
Warns when a toJson
method references a non-encodable object.
Passing results of such toJson
methods to jsonEncode
will result in a runtime exception.
⚙️ Config
Set methods
(default is empty) to configure a list of additional methods that should be checked.
dart_code_metrics:
...
rules:
...
- avoid-not-encodable-in-to-json:
methods:
- customToJson
Example
❌ Bad:
class SomeClass {
final String value;
const SomeClass(this.value);
}
class WithJson {
Map<String, Object?> toJson(Set<String> values) => {
'key': values, // LINT
'function': () => null, // LINT
'instance': SomeClass(''), // LINT
};
}
✅ Good:
class SomeClass {
final String value;
const SomeClass(this.value);
Map<String, Object?> toJson() => {'some': 'class'};
}
class WithJson {
Map<String, Object?> toJson(Set<String> values) => {
'key': values.toList(),
'instance': SomeClass(''),
};
}