modelTemplate function

String modelTemplate(
  1. String name,
  2. List<FieldSpec> fields
)

Code templates shared by the generators. Names are derived from a single input via Naming; output adapts to the modules installed in ProjectContext (e.g. the widget library and design tokens are used only when present). An immutable data class with fromJson / toJson / copyWith / toString, generated from a --fields spec.

Implementation

/// An immutable data class with `fromJson` / `toJson` / `copyWith` / `toString`,
/// generated from a `--fields` spec.
String modelTemplate(String name, List<FieldSpec> fields) {
  final className = Naming.pascal(name);
  final effective =
      fields.isEmpty ? const [FieldSpec('id', 'String', false)] : fields;

  final declarations = effective.map((f) => '  ${f.declaration}').join('\n');
  final ctorParams = effective.map((f) => '    ${f.ctorParam},').join('\n');
  final fromJson = effective
      .map((f) => '        ${f.name}: ${f.fromJsonExpr()},')
      .join('\n');
  final toJson = effective.map((f) => '        ${f.toJsonEntry()}').join('\n');
  final copyParams =
      effective.map((f) => '    ${f.type}? ${f.name},').join('\n');
  final copyAssign = effective
      .map((f) => '      ${f.name}: ${f.name} ?? this.${f.name},')
      .join('\n');
  final toStringFields =
      effective.map((f) => '${f.name}: \$${f.name}').join(', ');

  return '''
/// Data model for $className. Generated by river_cli.
class $className {
$declarations

  const $className({
$ctorParams
  });

  factory $className.fromJson(Map<String, dynamic> json) => $className(
$fromJson
      );

  Map<String, dynamic> toJson() => {
$toJson
      };

  $className copyWith({
$copyParams
  }) =>
      $className(
$copyAssign
      );

  @override
  String toString() => '$className($toStringFields)';
}
''';
}