checkerForField method

SharedChecker<Model> checkerForField(
  1. FieldElement field
)
inherited

Return a SharedChecker for a type via the corresponding parameter in the constructor.

This is necessary to support behavior where type definitions (particularly nullability) in a class member definition might not match that of the constructor. In this instance, we want to infere type from the constructor, not the field. This requires the class member name to match the parameter name in the constructor. We only want to apply this logic to deserialization, so serialization will always respect the type of the member field.

Ex:

  class MyClass {
    final String field;

    MyClass({String? field}): field = field ?? 'default';
  }

Implementation

SharedChecker checkerForField(FieldElement field) {
  if (!doesDeserialize) return checkerForType(field.type);
  final defaultConstructor = _firstWhereOrNull<ConstructorElement>(
    element.constructors,
    (e) => !e.isFactory && e.name.isEmpty,
  );
  final defaultConstructorParameter = defaultConstructor?.parameters != null
      ? _firstWhereOrNull<ParameterElement>(
          defaultConstructor!.parameters,
          (e) => e.name == field.name,
        )
      : null;
  return checkerForType(defaultConstructorParameter?.type ?? field.type);
}