generateInstances method
Generate instances for the data classes file.
Implementation
void generateInstances(
final StringBuffer buffer,
final ClassModel model,
) {
for (final InstanceModel instance in model.instances) {
final Object? fields = instance.fields;
bool isConst = true;
if (fields is Map<String, Object?>) {
if (isConst = model.fields
.where(
(final _) =>
_.type == FieldType.$datetime ||
_.type == FieldType.$$datetime,
)
.every((final _) => fields[_.key] == null)) {
isConst = model.fields.where((final _) {
if (_.type == FieldType.$object || _.type == FieldType.$$object) {
String $type = _.reference.split('.').last;
if ($type.endsWith('[]')) {
$type = $type.substring(0, $type.length - 2);
}
return models.any((final _) => _.key == $type || _.name == $type);
}
return false;
}).every((final _) {
final Object? value = fields[_.key];
return _.type == FieldType.$object && value is! String ||
_.type == FieldType.$$object &&
(value is! Iterable<Object?> ||
value.every((final _) => _ is! String));
});
}
} else if (fields is Iterable<Object?>) {
for (int index = 0; index < model.fields.length; index++) {
final Object? value = fields.elementAt(index);
final FieldModel field = model.fields.elementAt(index);
if ((field.type == FieldType.$datetime ||
field.type == FieldType.$$datetime) &&
value != null) {
isConst = false;
break;
} else if (field.type == FieldType.$object ||
field.type == FieldType.$$object) {
String $type = field.reference.split('.').last;
if ($type.endsWith('[]')) {
$type = $type.substring(0, $type.length - 2);
}
if (models.any((final _) => _.key == $type || _.name == $type)) {
if (field.type == FieldType.$object && value is String ||
field.type == FieldType.$$object &&
value is Iterable<Object?> &&
value.any((final _) => _ is String)) {
isConst = false;
break;
}
}
}
}
}
buffer
..writeDoc(
instance.doc == null
? 'The instance of a [${model.name}].'
: instance.doc!,
indent: 2,
)
..write('${isConst ? 'const' : 'final'} '
'${model.name} ${instance.name} = ${model.name}(');
if (fields is Map<String, Object?>) {
for (final MapEntry<String, Object?> instanceField in fields.entries) {
if (instanceField.value != null) {
final FieldModel field = model.fields
.firstWhere((final _) => _.key == instanceField.key);
buffer
..write('${field.name}: ')
..write(_renderDefault(model, field, instanceField.value))
..writeln(',');
}
}
} else if (fields is Iterable<Object?>) {
for (int index = 0; index < model.fields.length; index++) {
if (fields.elementAt(index) != null) {
final FieldModel field = model.fields.elementAt(index);
buffer
..write('${field.name}: ')
..write(
_renderDefault(model, field, fields.elementAt(index)),
)
..writeln(',');
}
}
}
buffer.writeln(');');
}
}