Skip to main content

avoid-not-encodable-in-to-json

added in: 1.14.0
⚙️
Pro+
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 the list of additional methods that should be checked (example).

analysis_options.yaml
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: This expression is not encodable and will lead to an error when passed to 'jsonEncode'. Try converting it to 'List'.
'function': () => null, // LINT: This expression is not encodable and will lead to an error when passed to 'jsonEncode'. Ensure it implements 'toJson' or try replacing it with a different expression.
'instance': SomeClass(''), // LINT: This expression is not encodable and will lead to an error when passed to 'jsonEncode'. Ensure it implements 'toJson' or try replacing it with a different expression.
};
}

✅ 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(), // Correct, converted to List
'instance': SomeClass(''), // Correct, has custom 'toJson'
};
}

Example with "methods"

Config
analysis_options.yaml
dart_code_metrics:
rules:
- avoid-not-encodable-in-to-json:
methods:
- customToJson

❌ Bad:

class WithJson {
// Also checked
Map<String, Object?> customToJson(Set<String> values) => {
'key': values, // LINT: This expression is not encodable and will lead to an error when passed to 'jsonEncode'. Try converting it to 'List'.
'function': () => null, // LINT: This expression is not encodable and will lead to an error when passed to 'jsonEncode'. Ensure it implements 'toJson' or try replacing it with a different expression.
};
}

Additional Resources