parseModelFile function

ModelDefinition parseModelFile(
  1. File file
)

Implementation

ModelDefinition parseModelFile(File file) {
  final yaml = loadYaml(file.readAsStringSync()) as YamlMap;

  final className = yaml['class'] as String;

  final fields = <ModelField>[];
  final yamlFields = yaml['fields'] as YamlList;
  for (var item in yamlFields) {
    if (item is YamlMap) {
      final dartName = item.keys.first.toString();
      final dartType = item.values.first.toString();

      // Check if there’s a "key" or "name" (JSON key override)
      final jsonKey = item['key']?.toString() ?? dartName;
      final String? defaultValue = item['default']?.toString();
      List<String> enumValues = [];

      if ((dartType == 'enum' || dartType == 'enum?') && item['values'] == null) {
        throw const FormatException("""
 Invalid Enum format : Define enum values in the yaml file
          Example:
            - status: enum
              values: ['value1', 'value2', 'value3']
          """);
      }

      if ((dartType == 'enum' || dartType == 'enum?') && (item['values'] as YamlList).isNotEmpty) {
        enumValues = (item['values'] as YamlList).map((e) => e.toString()).toList();
      }

      fields.add(ModelField(dartName, dartType, jsonKey: jsonKey, defaultValue: defaultValue, enumValues: enumValues));
    } else {
      throw FormatException('Invalid field format: $item');
    }
  }

  return ModelDefinition(
    className: className,
    fields: fields,
    constructor: yaml['constructor'] ?? true,
    equatable: yaml['equatable'] ?? true,
    copyWith: yaml['copyWith'] ?? false,
    fromMap: yaml['fromMap'] ?? true,
    toMap: yaml['toMap'] ?? false,
  );
}