Skip to Content
DocsAckAdvancedModel Code Generation

Model Code Generation

Ack supports code generation in three workflows: start from an Ack schema, start from a Dart class, or start from a .schema.json document.

Starting pointTriggerGenerated output
A top-level Ack schema (final userSchema = ...)@Schemable()Immutable User class, User.schema, parse/safeParse, fromJson/toJson, copyWith in <file>.g.dart
A Dart class or sealed union (final class Account)@Schemable()_accountSchema codec, AccountSchema facade, and _$AccountAck mixin in <file>.g.dart
A JSON Schema asset (lib/**/*.schema.json)ack_generator:ack_json_schema in build.yaml<name>.schema.dart + <name>.schema.g.dart with typed @Schemable() models or validated value models

@Schemable(), @AckKey, and the Is…/Has… rule annotations (such as @IsRequired() and @HasMinLength(2)) all come from package:ack/ack.dart (and package:ack/annotations.dart). There is no @AckSchema() annotation; AckSchema<Boundary, Runtime> is the runtime type returned by factories such as Ack.string() and Ack.object().

Upgrading from Ack 1.x? See the What’s New & Migration Guide for a complete table of changes, removed 1.x annotations, and drop-in 2.0 substitutions.

Install the generator

dart pub add ack:^2.0.0-beta.3 dev:ack_generator:^2.0.0-beta.3 dev:build_runner

Every annotated library needs the generated part:

part 'models.g.dart';

Run the generator after adding or changing a model:

dart run build_runner build

A working example of both directions

This file contains one schema-first model and one class-first model. Both use the same builder and generated part.

import 'package:ack/ack.dart'; part 'models.g.dart'; // Schema-first: write the schema; Ack generates Order. @Schemable() final orderSchema = Ack.object({ 'id': Ack.string(), 'total': Ack.double().positive(), }); // Class-first: write Account; Ack generates AccountSchema. @Schemable(caseStyle: AckCaseStyle.snake) final class const Account({ @HasMinLength(2) required final String displayName, @IsEmail() required final String email, required final String? middleName, final Uri? website, final String role = 'member', }) with _$AccountAck { static final schema = AccountSchema.schema; static final fromJson = AccountSchema.fromJson; }

After generation, both directions have a typed parsing and JSON boundary:

final order = Order.parse({'id': 'o1', 'total': 12.5}); print(order.total); // double final account = Account.fromJson({ 'display_name': 'Ada', 'email': 'ada@example.com', 'middle_name': null, }); print(account.role); // member print(account.toJson()); // validated snake_case JSON

The schema-first and class-first declarations may live in the same library. Ordinary @JsonSerializable() classes keep their separate .g.dart file, but do not put @Schemable() and @JsonSerializable() on the same class.

name applies only to a top-level schema. schemaName, description, caseStyle, the discriminator options, unknownProperties, and captureField apply only to a class. Generation fails when an option is set for the other target.

Schema-first: @Schemable() on a top-level schema

Use schema-first generation when the wire contract is the primary artifact. The source schema owns validation, defaults, codecs, and JSON Schema export; Ack generates the stored Dart type around it.

@Schemable() final userSchema = Ack.object({ 'id': Ack.string().uuid(), 'email': Ack.string().email().nullable(), 'tags': Ack.list(Ack.string()).optional(), });

userSchema generates User: a trailing Schema is removed and no suffix is added. Use @Schemable(name: 'AppUser') when you need an exact class name.

Generated models provide:

  • an unchecked constructor with stored typed fields;
  • User.parse and User.safeParse for validated input;
  • User.fromJson, toJson, and safeToJson for the JSON boundary;
  • generated copyWith, deep collection-aware ==/hashCode, and toString;
  • User.schema, the model-valued schema for composition such as Ack.list(User.schema); it is a shorthand for User.$ack.modelSchema and is omitted when the model has a field or discriminator named schema, the annotated declaration is named schema, or the library imports a prefix named schema;
  • a public User.$ack adapter used by nested generated models.

The generator supports object and value roots, literals, enums, lists, sets, string-keyed maps, built-in and custom bidirectional codecs, named nested models, aliases, defaults, additional properties, named lazy recursion, and same-library discriminated unions. Stored collections are copied recursively into unmodifiable collections.

Fields may use Ack.any() for JSON-safe Object values and Ack.map(...) for string-keyed Map<String, T> values. Ack.any().nullable() infers Object?, and Ack.map(Ack.any().nullable()) infers Map<String, Object?>.

One-way transforms cannot back a generated model because there is no encoder. Generation also rejects nullable roots, Ack.any() and Ack.map() roots, Ack.anyOf(), bare Ack.instance<T>(), anonymous inline object fields, unresolved dynamic schema factories, and cross-library union branches.

Schema-first unions

Each branch must be a named @Schemable() object schema in the same library:

@Schemable() final catSchema = Ack.object({'lives': Ack.integer()}); @Schemable() final dogSchema = Ack.object({'breed': Ack.string()}); @Schemable() final petSchema = Ack.discriminated( discriminatorKey: 'type', schemas: {'cat': catSchema, 'dog': dogSchema}, );

This generates a sealed Pet base plus Cat and Dog branches.

Class-first: @Schemable() on a class

Use class-first generation when the Dart class is the primary artifact. Ack reads the fields that the class’s constructor declares and generates a codec schema whose runtime value is your class. The examples use Dart 3.13 primary constructors, so each declaring parameter carries its own annotations:

@Schemable(caseStyle: AckCaseStyle.snake) final class Profile({ @HasMinLength(2) required final String displayName, @IsEmail() required final String email, final String role = 'member', }) with _$ProfileAck { static final schema = ProfileSchema.schema; static final fromJson = ProfileSchema.fromJson; }

Ack generates a public ProfileSchema facade backed by a library-private codec variable:

  • ProfileSchema.parse and safeParse validate input;
  • ProfileSchema.fromJson is the one-argument map convenience;
  • ProfileSchema.encode and safeEncode validate while encoding;
  • ProfileSchema.toJsonSchema() exports the boundary JSON Schema;
  • ProfileSchema.toSchemaModel() exports Ack’s canonical schema model;
  • ProfileSchema.schema is the typed model codec used for composition;
  • ProfileSchema.wireSchema validates like schema and returns the JSON map instead of the model.

Every instantiable @Schemable class and implicit sealed-union branch must be declared final class, initialize its fields through an unnamed generative or primary constructor, contain only final stored fields, and apply its generated _$ClassAck mixin. The mixin supplies toJson(), safeToJson(), a typed copyWith where omission keeps the current value, explicit null clears a nullable field, and a wrongly typed argument is a compile-time error, and deep collection-aware ==, hashCode, and toString. A sealed abstract base receives union serialization only.

Values created by ProfileSchema.parse or Profile.fromJson receive recursive unmodifiable copies of list, set, map, and captured-extra values. Ack cannot rewrite a hand-written constructor, so direct construction and collection replacements passed to copyWith must defensively copy mutable inputs in the source class when that guarantee is required.

Generated toJson() and safeToJson() methods delegate through that same facade. Ack cannot inject static members or constructors into a hand-written class, so the recommended conventions are one-line static tear-offs/fields:

static final schema = ProfileSchema.schema; static final fromJson = ProfileSchema.fromJson;

static final schema = ProfileSchema.schema; attaches the generated codec directly to Profile.schema so callers can write Profile.schema.parse(...), Profile.schema.toJsonSchema(), or Ack.list(Profile.schema), and other libraries only need to import Profile. Both lines are optional: if omitted, ProfileSchema still provides every static entry point and nested @Schemable() models still compose automatically. Generation rejects a schema static whose type produces another class.

If a framework specifically requires a factory constructor for fromJson, use:

factory Profile.fromJson(Map<String, dynamic> json) => ProfileSchema.fromJson(json);

An explicit function-field type is also valid but normally unnecessary:

static final Profile Function(Map<String, dynamic>) fromJson = ProfileSchema.fromJson;

Use @Schemable(description: ...) and a single-line @description tag in a /// or /** */ doc comment on classes, fields, or constructor parameters to export schema descriptions. Only the text after the tag, on the same line, is exported. Untagged prose does not become schema data. Explicit annotation text on @Schemable(description: ...) takes precedence over a class doc tag. Blank or duplicate tags fail generation. @description is an Ack convention, not a Dart annotation.

A class description applies to its object schema and model codec. This includes sealed union bases and branches. A field description applies at its property. It does not change a nested model’s own description.

/// Tracks one unit of work. This prose is not exported. @Schemable(description: 'A task the person can complete.') final class const Task({ required final String id, /// @description What to do. required final String title, }) with _$TaskAck; TaskSchema.toJsonSchema()['description']; // 'A task the person can complete.'

Use @Schemable(schemaName: 'WireProfileSchema') to override the exact public facade name. It must be a public UpperCamel identifier. The private backing name remains derived from the model class, and no public lower-camel alias is generated.

Classic constructors

A classic constructor works the same and generates identical code. Put the annotations on the fields it initializes:

@Schemable(caseStyle: AckCaseStyle.snake) final class Profile with _$ProfileAck { Profile({ required this.displayName, required this.email, this.role = 'member', }); @HasMinLength(2) final String displayName; @IsEmail() final String email; final String role; static final schema = ProfileSchema.schema; static final fromJson = ProfileSchema.fromJson; }

Presence comes from the constructor

DeclarationGenerated field schemaInput behaviorEncoding behavior
required T<schema>Required, non-nullAlways present
required T?<schema>.nullable()Required, may be nullPresent even when null
Optional T?<schema>.optional().nullable()May be omittedOmitted when null
Constructor default, such as this.tools = const []<schema>.withDefault(const [])A missing key uses the default; JSON null requires T?A null stored value encodes as the default

In 2.0.0-beta.2, a constructor default fills an omitted key. A present JSON null is rejected for T, including defaulted fields. Declare T? to accept it, or use the existing @IsNotNull() to reject it on a nullable field. With String? label and this.label = 'fallback', missing input and JSON null both parse as 'fallback'. A directly constructed label: null now encodes as 'fallback' too. With this.label = null, missing input and JSON null parse as null and the encoded object keeps the key with a null value. These changes are breaking relative to beta.1.

Presence and nullability rules also apply to fields backed by registered or type-owned custom schemas. A custom schema’s own default does not become a field default: required fields and optional fields export no inherited default. Only the field’s default policy supplies an exported default. Custom codecs keep their value validation and encoding; their wrapper flags cannot make a required field optional or a non-nullable field accept null.

Three annotations control presence and null acceptance. They change the JSON contract only; Dart nullability and the constructor stay as written, and unannotated fields keep constructor inference.

AnnotationEffect
@IsOptional()The key may be omitted. Valid when the constructor can accept a missing value: an optional or defaulted parameter, or required T? (a missing key then parses as null and encoding omits a null value). On required T generation fails.
@IsRequired()The key must be present. On an optional T? field JSON null is still accepted and encoding writes the key even when the value is null. On a defaulted field, input no longer falls back to the default.
@IsNotNull()A present JSON null is rejected; key presence is unchanged. Use it on T? and JsonMaybe<T> fields; non-nullable fields such as Map<String, V> already reject JSON null. A missing optional key still parses as null. Encoding uses a non-null constructor default when one is inferred; otherwise it omits a null Dart value.

@IsOptional() is not a no-op on a defaulted field. Without it, this.tools = const [] generates .withDefault(const []). With it, the field generates .optional(): a missing key still gets the constructor default, but JSON null is rejected for a non-nullable type and the exported JSON Schema carries no default.

@IsOptional() alone on String? still accepts JSON null. Add @IsNotNull() when a present value must not be null:

@Schemable() final class const Example({@IsOptional() @IsNotNull() final String? label}) with _$ExampleAck;

ExampleSchema.parse({}) yields label: null, {"label": "hello"} succeeds, and {"label": null} fails. Encoding omits a null Dart value. Here @IsOptional() only restates what the constructor already infers; @IsNotNull() is the annotation that changes null acceptance.

The generator infers String, bool, numeric types, DateTime, Uri, Duration, enums, nested lists, and sets. Sets use a list codec. Open JSON values use the Dart types you already write:

Dart fieldInferred schema
ObjectAck.any()
Object?Ack.any().nullable(); presence rules match String?
List<Object>Ack.list(Ack.any())
Map<String, T>Ack.map(<schema for T>)
Map<String, Object?>Ack.map(Ack.any().nullable())
JsonMaybe<T>Optional-and-nullable <schema for T>; omitted when JsonAbsent, null when JsonValue(null)

Use JsonMaybe<T> when a PATCH request needs to distinguish an omitted field (JsonAbsent) from an explicit null (JsonValue(null)):

@Schemable() final class const ProfilePatch({ final JsonMaybe<String> bio = const JsonMaybe.absent(), }) with _$ProfilePatchAck { static final schema = ProfilePatchSchema.schema; static final fromJson = ProfilePatchSchema.fromJson; } // Omitted key -> JsonAbsent(); toJson() returns {} final unchanged = ProfilePatch.fromJson({}); // Explicit null -> JsonValue(null); toJson() returns {'bio': null} final cleared = ProfilePatch.fromJson({'bio': null});

Object means a JSON-safe value (a finite number, string, boolean, list, or string-keyed map of those values), not an arbitrary Dart instance, so a DateTime inside an Object or Map<String, Object?> field fails validation. Map values may be null only when the value type is nullable. List<Object?> stays rejected because Ack.list has no nullable-item contract. Parsed Object values are recursively unmodifiable, like other stored collections.

Rule annotations follow the field type. Is… names what the value is, and Has… names a bound or property it has:

  • presence & nullability: @IsRequired, @IsOptional, @IsNotNull;
  • numeric: @HasMin, @HasMax, @IsMultipleOf, @IsPositive, @IsNegative;
  • strings: @HasMinLength, @HasMaxLength, @HasMatch, @IsEmail, @IsNotEmpty;
  • string formats: @IsUrl, @IsUri, @IsUuid, @IsDate, @IsDateTime, @IsIp (version: 4 or 6 for one family);
  • lists and sets: @IsNotEmpty, @HasMinItems, @HasMaxItems, @HasUniqueItems.

@HasMatch is the annotation form of Ack.string().matches(...). Like matches(), it is not anchored: the pattern may match anywhere in the string, so use ^...$ for a full-string match. Numeric constraint values must be finite. On a Set<Set<T>> field the collection constraints apply to the outer set.

Use caseStyle for model-wide JSON names. Supported values are none, snake, kebab, pascal, and screamingSnake. Use @AckKey('wire_name') on the field or primary constructor parameter for a single wire-name override. Ack resolves each wire key once and uses it for both validation and JSON mapping. JsonConverter annotations are rejected so the Ack schema and generated JSON mapping cannot diverge.

Custom schemas and types that own their schema

When a class-first field has a custom type T (including inside List<T>, Set<T>, Map<String, T>, JsonMaybe<T>, or generic Box<T>), Ack resolves its schema in the following priority order:

  1. @Schemable(schemas: [...]) on the class, enclosing union base, current library; directive, or an imported library; directive;
  2. Type-owned schema (T.schema / T.schema<A>(...)) on the type itself;
  3. Automatic current-library detection: a unique top-level AckSchema<Boundary, T> variable, getter, or zero-argument function in the current library.

A type you own can declare its schema once, as a static member named schema. Any field of that type then resolves to it with no annotation on the field, also as a List or Set item and as a Map value:

final class Slot { const Slot(this.id); final String id; static final schema = Ack.string().codec<Slot>( decode: Slot.new, encode: (slot) => slot.id, ); } @Schemable() final class const Section({ required final Slot header, // Slot.schema final Slot? footer, // Slot.schema, optional and nullable required final List<Slot> children, // Ack.list(Slot.schema) }) with _$SectionAck;

The static can be a field or a getter typed AckSchema<Boundary, Slot>. It works the same on an extension type; declare it implements Object so it satisfies the codec’s Object bound:

extension type const WidgetId(String value) implements Object { static final schema = Ack.string().codec<WidgetId>( decode: WidgetId.new, encode: (id) => id.value, ); }

An enum that declares a static schema resolves to it as well, instead of the default Ack.enumValues, so it can map custom wire values.

A static field cannot mention a class’s type parameters, so a generic type declares a static generic method instead. It takes one of two forms. With no parameters, the generator calls it with the field’s type arguments, written as they are, including void and Object?:

final class Command<A> { const Command(this.name); final String name; static AckSchema<String, Command<A>> schema<A>() => Ack.string().codec<Command<A>>( decode: Command<A>.new, encode: (command) => command.name, ); } // final Command<CompletionAction> open; -> Command.schema<CompletionAction>() // final Command<void> close; -> Command.schema<void>()

When the schema needs to validate the type argument itself, declare one positional parameter per type parameter, each typed AckSchema<Object, A> for its type parameter A. The generator passes the schema it infers for each type argument: a facade for a @Schemable class, a built-in schema for a primitive, and the collection schema for a List:

final class Box<A extends Object> { const Box(this.value); final A value; static AckSchema<Object, Box<A>> schema<A extends Object>( AckSchema<Object, A> value, ) => value.codec<Box<A>>(decode: Box<A>.new, encode: (box) => box.value); } // final Box<Row> row; -> Box.schema<Row>(RowSchema.schema) // final Box<String> title; -> Box.schema<String>(Ack.string()) // final Box<List<Row>> rows; -> Box.schema<List<Row>>(Ack.list(RowSchema.schema))

Generation checks the parameter count and that each parameter is a schema of its type argument. A type argument without an inferable schema fails with the usual unsupported-type message.

The schema must produce the field’s type; generation fails otherwise, for example when Slot.schema produces a String or when a generic type offers a static field instead of a schema<A>() method. Schema-first objects can reference the same members, such as 'header': Slot.schema or 'open': Command.schema<void>().

External types and library registries

For a third-party type you cannot edit:

  • In the same library: declare a unique top-level AckSchema<Boundary, T> variable, getter, or zero-argument function — Ack detects it automatically.
  • Across a class, union, or library: pass top-level schema function tear-offs in @Schemable(schemas: [colorSchema]) on the class, union base, or library; directive (including an imported shared library; directive).
@Schemable(schemas: [colorSchema]) library; import 'package:ack/ack.dart'; import 'package:color_library/color.dart'; part 'theme.g.dart'; AckSchema<String, Color> colorSchema() => Ack.string().codec<Color>( decode: Color.parse, encode: (color) => color.hex, ); @Schemable() final class const Theme({required final Color primary}) with _$ThemeAck;

Non-String map keys and dynamic are rejected because they do not provide a static schema; use Object? for an open JSON value. Automatic List<T> and Set<T> inference also requires non-nullable element types because Ack.list has no nullable-item contract.

Class-first unions

Annotate a sealed base with a discriminator key. Concrete branches in the same library are included automatically, and inherited constructor fields may use super parameters:

@Schemable(discriminatorKey: 'type') sealed class const Pet({required final String id}) with _$PetAck; @Schemable(discriminatorValue: 'cat') final class const Cat({required super.id, required final int lives}) extends Pet with _$CatAck; final class const Dog({required super.id, required final String breed}) extends Pet with _$DogAck;

The base and every concrete branch receive facades (PetSchema, CatSchema, and DogSchema), including branches without their own @Schemable annotation.

Without an explicit discriminatorValue, the wire value is the verbatim class name (Dog above). Set explicit values when the wire format must remain stable through class renames. Class-first anyOf and value roots are not supported; use schema-first generation for those shapes.

Additional properties

Raw object validation and class projection are separate decisions. Ack.object(..., additionalProperties: true) accepts unknown keys and preserves them in the returned JsonMap. A later class-first projection then decides whether the Dart class rejects, discards, or captures those keys.

@Schemable uses AckUnknownPropertyPolicy through unknownProperties:

  • reject (default) fails validation on unknown properties;
  • discard accepts unknown properties but does not store them. Use it only for tolerant, read-only consumers;
  • capture stores them in captureField, which defaults to additionalProperties and may be args.

Capture requires a declared Map<String, Object?> field initialized by the constructor. Encoding writes extras first, so a declared field or discriminator cannot be replaced by an extra value. Models that must round-trip unknown keys must use capture, not discard. Hand-written constructors can call deepUnmodifiableJsonMap to detach and recursively freeze direct map inputs without validating them.

Reusing generated schemas

Nested class-first fields compose through the target facade (or Address.schema when declared on the class) automatically:

import 'address.dart' as address; @Schemable() final class const Order({required final address.Address shipping}) with _$OrderAck; // Generated field schema: address.AddressSchema.schema

Schema-first declarations can use Address.schema or the facade explicitly:

@Schemable() final envelopeSchema = Ack.object({ 'address': address.AddressSchema.schema, 'history': Ack.list(address.AddressSchema.schema), });

Class-first fields may also use a model generated from a @Schemable() top-level schema; Ack composes through the generated Address.$ack.schema. Both directions work on the first clean build, including nullable values, lists, nested lists, and sets. A model generated in the same build cannot yet be a Map value; generation reports that case.

A generated part cannot add imports, so every type a field names must be visible in the annotated library itself. A type reached only through a typedef from another library, or a codec’s runtime type from a library you did not import, fails generation with the library to import.

When importing with show / hide combinators, if a class-first model declares static final schema = AddressSchema.schema;, importing libraries only need to expose Address:

import 'address.dart' show Address;

If Address does not declare a static schema, expose both the hand-written model and its generated facade:

import 'address.dart' show Address, AddressSchema;

For schema-first composition it means the annotated schema and generated model (addressSchema plus Address). Visibility may be split across multiple imports using the same prefix, but every barrel export layer must expose the generated companion. Prefixed imports avoid ambiguity when two libraries declare the same model name. Deferred imports are unsupported.

Automatic recursive class-first schemas are not yet defined. For self or mutually recursive contracts, use schema-first named Ack.lazy schemas.

Which direction should you choose?

Put @Schemable() on a top-level schema when you want to design the boundary schema first, generate the whole model, or model a scalar or collection root. Put it on a class when you already own the class, want to keep methods and constructors in source, or prefer field annotations over a separate object schema.

This choice is per model, not per project. A migration can keep existing schema-first types while new domain-owned types use class-first generation.

Limit generation in larger projects

Scope ack_generator to your model files with generate_for:

targets: $default: builders: ack_generator:ack_generator: generate_for: [lib/models/**.dart]

Build checklist

  1. Add ack to dependencies and import package:ack/ack.dart.
  2. Add ack_generator and build_runner to dev dependencies.
  3. Declare part '<file>.g.dart'; in each annotated library.
  4. Put @Schemable() on a top-level schema or on a class.
  5. Run dart run build_runner build.

Migrating from 1.x

  • Remove ack_annotations, json_serializable, and json_annotation from pubspec.yaml (unless used by non-Ack classes), and import package:ack/ack.dart.
  • Replace part '<file>.ack.dart'; + part '<file>.ack.g.dart'; with a single part '<file>.g.dart';.
  • Replace @AckType(), @AckInfer(), and @AckModel() with @Schemable().
  • Replace top-level presence and constraint annotations (@Optional, @Required, @NotNull, @Min, @Max, @MinLength, @Matches, @Email, @DateTime, etc.) with the rule annotations (@IsOptional, @IsRequired, @IsNotNull, @HasMin, @HasMax, @HasMinLength, @HasMatch, @IsEmail, @IsDateTime, etc.).
  • Replace @JsonKey(name: '...') on @Schemable fields with @AckKey('...').

See the What’s New & Migration Guide for the complete substitution tables and side-by-side before/after examples.

Last updated on