avoid-not-encodable-in-to-json
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
dcm:
  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) => {
    // LINT: This expression is not encodable and will lead to an error when passed to 'jsonEncode'.
    //  Try converting it to 'List'.
    'key': values,
    // 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.
    '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(''),
  };
}
✅ 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
dcm:
  rules:
    - avoid-not-encodable-in-to-json:
        methods:
          - customToJson
❌ Bad:
class WithJson {
  // Also checked
  Map<String, Object?> customToJson(Set<String> values) => {
    // LINT: This expression is not encodable and will lead to an error when passed to 'jsonEncode'.
    //  Try converting it to 'List'.
    'key': values,
    // 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.
    'function': () => null,
  };
}