getBestConstructorsForMap method

List<ConstructorReflection<O>> getBestConstructorsForMap(
  1. Map<String, Object?> map, {
  2. FieldNameResolver? fieldNameResolver,
  3. FieldValueResolver? fieldValueResolver,
  4. bool allowEmptyConstructors = true,
  5. bool allowOptionalOnlyConstructors = true,
})

Returns an unmodifiable List of the best constructors to instantiate with map entries.

Implementation

List<ConstructorReflection<O>> getBestConstructorsForMap(
    Map<String, Object?> map,
    {FieldNameResolver? fieldNameResolver,
    FieldValueResolver? fieldValueResolver,
    bool allowEmptyConstructors = true,
    bool allowOptionalOnlyConstructors = true}) {
  fieldNameResolver ??= _defaultFieldNameResolver;

  var fieldsResolved = _resolveFieldsNames(fieldNameResolver, map);

  var presentFields = fieldsResolved.keys;

  List<String> presentParameters;

  if (map.length > fieldsResolved.length) {
    var mapUsedKeys = fieldsResolved.values.toList();
    var mapUnusedKeys = map.keys.where((k) => !mapUsedKeys.contains(k));

    presentParameters = <String>[...presentFields, ...mapUnusedKeys];
  } else {
    presentParameters = presentFields.toList();
  }

  var key = _KeyParametersNames(presentParameters, allowEmptyConstructors);

  var cache = getStaticInstance()._getBestConstructorForMapCache ??=
      <_KeyParametersNames, List<ConstructorReflection<O>>>{};

  var constructors = cache.putIfAbsent(key, () {
    key.sort();

    List<ConstructorReflection<O>> list;
    if (hasJsonNameAlias) {
      list = _getBestConstructorsForMapImpl(presentParameters,
          allowEmptyConstructors, allowOptionalOnlyConstructors, true);
      if (list.isEmpty) {
        list = _getBestConstructorsForMapImpl(presentParameters,
            allowEmptyConstructors, allowOptionalOnlyConstructors, false);
      }
    } else {
      list = _getBestConstructorsForMapImpl(presentParameters,
          allowEmptyConstructors, allowOptionalOnlyConstructors, false);
    }

    return list.length > 1
        ? ListSortedByUsage<ConstructorReflection<O>>(list)
        : UnmodifiableListView(list);
  });

  return constructors;
}