keyed_form_gen 0.1.0
keyed_form_gen: ^0.1.0 copied to clipboard
build_runner code generator for keyed_form_schema: turns a schema into immutable data models, keyed_form_core field references and type-safe validation functions.
// Uses the generated output of `tour_schema.dart`. Every name below —
// `TourSchema`, `StopSchema`, `TourFields`, `StopRef` — is generated by
// `keyed_form_gen` from the single `ks.object({...})` declaration in that file.
//
// dart run build_runner build # (re)generate lib/tour_schema.kfg.dart
// dart run lib/main.dart
import 'tour_schema.dart';
void main() {
// 1. Immutable data classes. `.create()` fills schema defaults and assigns
// a UUID `clientId` to every list row (so it is a `KeyedRow`).
final tour = TourSchema.create(
title: 'Ky',
stops: [
StopSchema.create(city: 'Kyoto', nights: 3),
StopSchema.create(city: '', nights: 2),
],
);
print(tour.stops.map((s) => s.clientId).toList()); // two generated uuids
// 2. Generated field references — write one field without rebuilding the
// whole aggregate. `stop(ref)` takes a record of clientId strings.
final ref = (stop: tour.stops.first.clientId);
final updated = TourFields.stop(ref).city.set(tour, 'Kyoto (Gion)');
print(TourFields.stop(ref).city.getOrNull(updated)); // Kyoto (Gion)
// `stop(ref)` itself is a reference to the whole row:
print(TourFields.stop(ref).getOrNull(updated)?.nights); // 3
// 3. Validation generated from the same schema — `FieldErrors` keyed by the
// same `FieldKey` the references carry.
final errors = updated.validate(); // == TourSchema.validateData(updated)
for (final key in errors.keys) {
print('${key.toPath()}: ${errors.byKey(key)}');
}
// title: Tour title needs at least 3 characters
// stops.['<uuid-of-second-stop>'].city: City is required
}