API Reference
This page is a curated quick reference for the core Ack classes, methods, and annotations. Use the generated API documentation for every public declaration and exact signatures; use the linked guides here for explanations and examples.
Core Ack Class
Entry point for creating schemas. See Schema Types.
Ack.string(): Creates aStringSchemafor validatingStringvalues.Ack.integer(): Creates anIntegerSchemafor finite numeric values with no fractional part. Losslessly normalizes inputs such as42.0toint.Ack.double(): Creates aDoubleSchemafor finite numeric values. Losslessly normalizes inputs such as42todouble.Ack.number(): Creates aNumberSchemafor finitenumvalues while preserving theirintordoublerepresentation.Ack.boolean(): Creates aBooleanSchemafor validatingboolvalues.Ack.list(AckSchema itemSchema): Creates aListSchemafor validating arrays. Nullable item schemas are not supported; make the list itself nullable instead.Ack.object(Map<String, AckSchema> properties): Creates anObjectSchemafor validating objects.Ack.enumValues(List<T> values): Creates anEnumSchema<T>for Dart enum types. Parses enum.namestrings into typed enum values. Pass typed enum values toencodeorsafeEncodefor the reverse direction. Preferred overenumStringwhen a Dart enum exists.Ack.enumString(List<String> values): Creates aStringSchemaconstrained to the given values. For ad-hoc string lists without a backing Dart enum.Ack.anyOf(List<AckSchema> schemas): Creates anAnyOfSchemafor union types.Ack.any(): Creates anAnySchemathat accepts any non-null JSON-safe value. Chain.nullable()to allownull.Ack.fromJsonSchema(Object document, {Uri? baseUri, Map<Uri, Object> documents = const {}, bool assertFormats = false}): Strictly imports a decoded draft 2020-12 or Draft-7 JSON Schema. Referenced documents must be supplied explicitly; Ack never fetches files or URLs.formatis treated as an annotation by default unlessassertFormats: true(or the schema’s$vocabularyrequiresformat-assertion); see format import.Ack.map(AckSchema valueSchema): Creates aMapSchemafor a JSON object with arbitrary string keys whose values all matchvalueSchema. UseAck.map(Ack.any().nullable())for aJsonMap.Ack.instance<T extends Object>(): Creates a schema that checks a value is a Dart instance ofT(runtime type check; handy as a codecoutputschema).Ack.codec(...)/Ack.date()/Ack.datetime()/Ack.uri()/Ack.duration(): Create codecs. See Codecs.Ack.lazy(String name, AckSchema Function() builder, {int maxDepth = 100}): Creates a memoized deferred schema reference for recursive schema graphs.maxDepthmust be at least1and limits parsing, runtime validation, and encoding. JSON Schema export renders Draft-7definitions/$refentries usingnamebut warns that the runtime-only depth limit was omitted.Ack.discriminated<T extends Object>(...): Creates a discriminated union schema. Branches may be plainObjectSchemaor transformed schemas whose base is anObjectSchema. The union owns the discriminator: branches normally omit it, boundary payloads must include it, compatible branch discriminator fields are allowed, and conflicts are rejected. Exported/generated branches expose the exact branch literal.
JSON Schema Import
See JSON Schema Integration for the supported draft 2020-12 subset, reference-bundle behavior, diagnostics, and examples.
JsonSchemaImportDiagnostic: Describes one import issue throughcode,documentUri,pointer,keyword, andmessage.JsonSchemaImportException: Thrown when an import encounters an unsupported assertion or cannot be completed safely. Itsdiagnosticslist identifies every reported issue.JsonSchemaValidationError: ASchemaValidationErrorreturned when a value fails an imported schema.keywordnames the failing keyword, anddocumentUriandpointerlocate it after$refresolution.keywordLocationis the evaluation path that reached it, including$ref.
AckSchema<Boundary, Runtime> (Base Class)
Base class for all schema types.
Primary Validation Methods
SchemaResult<Runtime> safeParse(Object? data, {String? debugName}): Validatesdataand returns aSchemaResult. Invalid input and recoverableExceptionvalues thrown by constraint, refinement, orCodecSchemadecode/encodecallbacks become validation failures (SchemaValidationError/SchemaTransformError/SchemaEncodeError), while programmerErrorvalues are rethrown with their original stack trace.Runtime? parse(Object? data, {String? debugName}): Validatesdataand returns the value; throwsAckExceptionon failure.SchemaResult<TOut> safeParseAs<TOut extends Object>(Object? data, TOut Function(Runtime?) map, {String? debugName}): Parses and maps the validated value toTOut. MapperExceptions becomeSchemaTransformErrorfailures; mapperErrorvalues are rethrown with their original stack trace.TOut parseAs<TOut extends Object>(Object? data, TOut Function(Runtime?) map, {String? debugName}): Throwing variant ofsafeParseAs.SchemaResult<Boundary> safeEncode(Runtime? value, {String? debugName}): Encodes a runtime value to the boundary representation.Boundary? encode(Runtime? value, {String? debugName}): Throwing variant ofsafeEncode.
Schema Modification Methods
AckSchema<Boundary, Runtime> nullable({bool value = true}): Returns a new schema that also acceptsnull.AckSchema<Boundary, Runtime> optional({bool value = true}): Returns a new schema marked as optional (for object fields).AckSchema<Boundary, Runtime> describe(String description): Attaches a description for documentation and JSON Schema generation.DefaultSchema<Boundary, Runtime> withDefault(Runtime value): Wraps the schema in aDefaultSchemathat suppliesvaluewhen the parse input isnull.
String and boolean schemas require their exact Dart runtime type. Numeric
schemas require a num and follow JSON Schema value semantics instead of the
platform-specific int/double representation: IntegerSchema normalizes
lossless zero-fraction values to int, DoubleSchema normalizes exactly
representable values to double, and NumberSchema preserves the input
representation. Integer and double branches therefore overlap for integral
values in Ack.anyOf; the first matching branch determines the runtime value.
For non-num boundary types (e.g. numeric strings), use
transform or
codec to convert before validation.
Custom Validation Methods
AckSchema<Boundary, Runtime> constrain(Constraint<Runtime> constraint, {String? message}): Adds a constraint and optionally overrides its message. The constraint must mix inValidator<Runtime>, or anArgumentErroris thrown.AckSchema<Boundary, Runtime> withConstraint(Constraint<Runtime> constraint): Adds a constraint directly (no message override;constraindelegates here).AckSchema<Boundary, Runtime> refine(bool Function(Runtime) validate, {String message = 'The value did not pass the custom validation.'}): Adds a custom validation predicate with an optional error message.CodecSchema<Boundary, R> transform<R>(R Function(Runtime) transformer): Transforms validated runtime values toR(parse-only; encode fails).
Utility Methods
Map<String, Object?> toJsonSchema(): Returns a JSON Schema map via the canonicalAckSchemaModelboundary, preserving imported Draft 2020-12 resources by default and emitting Draft-7 for native Ack schemas.Map<String, Object?> toJsonSchemaDraft7(): Lowers imported schemas into the legacy Draft-7definitions/$refrepresentation when possible.AckSchemaModel toSchemaModel(): Returns the canonical, target-independent boundary model for schema adapters (preserving imported Draft 2020-12 resources by default), including export warnings.AckSchemaModel toSchemaModelDraft7(): Returns the canonical boundary model with imported schemas lowered to Draft-7definitions/$refwhen possible.
See also Schema Types for detailed usage examples.
StringSchema
Schema for validating strings. See String Validation.
Length Constraints
minLength(int min): Minimum string lengthmaxLength(int max): Maximum string lengthlength(int exact): Exact string lengthnotEmpty(): String must not be empty (equivalent tominLength(1))
Pattern Matching
matches(String pattern, {String? example, String? message}): Must match a regex pattern. Patterns are not automatically anchored — use^...$for full-string matching. See String validation for details.contains(String pattern, {String? example, String? message}): Must contain the pattern anywhere in the string.startsWith(String value): Must start withvalue.endsWith(String value): Must end withvalue.
Format Validation
email(): Must be valid email formaturl(): Must be valid URL format (alias foruri())uri(): Must be a valid absolute URI with a scheme and hostuuid(): Must be valid UUID formatip({int? version}): Must be valid IP address (version 4 or 6)ipv4(): Must be valid IPv4 addressipv6(): Must be valid IPv6 address
Date and Time
date(): Must be valid ISO 8601 date (YYYY-MM-DD)datetime(): Must be a valid ISO 8601 datetime; announced RFC leap seconds are accepted and preserved as stringstime(): Must be valid time format (HH:MM:SS)
Transformations
trim(): Removes leading and trailing whitespacetoLowerCase(): Converts to lowercasetoUpperCase(): Converts to uppercase
IntegerSchema / DoubleSchema / NumberSchema (Number Schemas)
Schemas for validating numeric values. IntegerSchema accepts finite num
values with no fractional part when conversion to int is lossless.
DoubleSchema accepts finite num values when conversion to double is
lossless. NumberSchema accepts finite num values without changing their
runtime representation. See
Number Validation.
Each method’s parameter type matches the schema’s runtime type: int for IntegerSchema, double for DoubleSchema, and num for NumberSchema.
min(N limit): Minimum value (inclusive)max(N limit): Maximum value (inclusive)greaterThan(N limit): Must be greater than limit (exclusive)lessThan(N limit): Must be less than limit (exclusive)positive(): Must be greater than 0negative(): Must be less than 0multipleOf(N factor): Must be a multiple of the factorfinite(): Must be finite (DoubleSchemaandNumberSchema; already the default)safe(): Must be within safe integer range (IntegerSchemaonly)
BooleanSchema
Schema for validating booleans. Validates true and false values strictly — non-boolean inputs are rejected. For boundary types that arrive as strings (e.g. "true"/"false"), use a transform or codec to convert before validation.
ListSchema<T>
Schema for validating arrays. See List Validation.
minItems(int min): Minimum number of items (alias:minLength)maxItems(int max): Maximum number of items (alias:maxLength)exactLength(int exact): Exact number of items (alias:length)nonEmpty(): List must have at least one item (alias:notEmpty)unique(): All items must be unique
ObjectSchema
Schema for validating objects (maps). See Object Validation.
- Constructed using
Ack.object(Map<String, AckSchema> properties, {bool additionalProperties = false}). - Use
.pick(List<String> keys)to create schema with only specified properties. - Use
.omit(List<String> keys)to create schema excluding specified properties. - Use
.extend(Map<String, AckSchema> newProperties)to add more properties. - Use
.partial()to make all properties optional. - Use
.strict()to disallow additional properties. - Use
.passthrough()to allow and preserve additional properties not defined in the schema. - Use
.merge(ObjectSchema other)to combine with another object schema.
deepUnmodifiableJsonMap(JsonMap value)
Creates a detached, recursively unmodifiable snapshot of nested maps, lists, and sets. It does not validate JSON shape or values. Use it in hand-written constructors that store dynamic JSON maps and need stable equality and hashes.
SchemaResult<T>
Object returned by safeParse(). See Error Handling.
bool isOk:trueif validation succeeded.bool isFail:trueif validation failed.T? getOrThrow(): Returns the validated value (which can benullfor a nullable schema), or throwsAckExceptionon failure.T? getOrNull(): Returns the validated value, ornullon failure.SchemaError getError(): Returns the validation error; only valid whenisFailistrue.T? getOrElse(T? Function() orElse): Returns the validated value, or callsorElseon failure.SchemaResult<R> map<R>(R Function(T?) transform): Maps the successful value to a new result type; propagates failures unchanged.R match<R>({required R Function(T?) onOk, required R Function(SchemaError) onFail}): Pattern-matches on success or failure.void ifOk(void Function(T?) action): Executesactiononly when the result is successful.void ifFail(void Function(SchemaError) action): Executesactiononly when the result is a failure.
SchemaError (and subclasses)
Represents a validation failure. See Error handling.
String message: Human-readable error message.SchemaContext context: Context about where the error occurred.
Subclasses:
TypeMismatchError: The input has the wrong Dart runtime type.SchemaConstraintsError: One or more constraint violations.SchemaNestedError: Validation failures in nested objects or arrays.SchemaValidationError: Custom refinement failures.SchemaTransformError: Decode/transform callback failures.SchemaEncodeError: Encode-path failures (non-nullable null, one-way transform, encoder threw, etc.).
Constraint<T>
Base class for custom validation rules. See Custom validation.
String constraintKey: Unique identifier for the constraint.String description: Human-readable description.Map<String, Object?> toMap(): Serializes the constraint for debugging.
Validator<T> (mixin)
Validation behavior mixin used with Constraint<T>.
bool isValid(T value): Returnstruewhen the value passes validation.String buildMessage(T value): Builds the validation failure message.ConstraintError? validate(T value): Validates a value and returns an error if invalid.
Additional schema types
Ack ships with a broad set of schema factories beyond what is listed here.
See Schema types for the full catalogue,
including Ack.date(), Ack.literal(), and list/object combinators.
Ack.discriminated(...)
Schema for polymorphic validation based on a string discriminator property.
- Branch schemas normally omit the discriminator field.
- The boundary payload must still contain the discriminator key.
- If a branch schema includes the discriminator field, it must be
Ack.literal(...)matching the branch key orAck.enumString(...)containing it. Broad, transformed, refined, or otherwise restrictive discriminator fields are rejected. - Exported and generated schemas expose each branch discriminator as an exact literal.
- Generated subtype
parse()andsafeParse()methods validate through the union’s effective branch.
Ack.lazy(...)
Schema reference for recursive object graphs.
- Created using
Ack.lazy<Boundary, Runtime>(name, builder).maxDepthdefaults to100and must be at least1; pass it explicitly only to override the default. - The builder is resolved once and memoized.
- Exceeding
maxDepthreturns a validation failure during parsing, runtime validation, or encoding. toJsonSchema()andtoSchemaModel()export Draft-7definitions/$refentries using the lazyname. The runtime-only depth limit cannot be represented by$ref, so exported schema models warn that it was omitted.- Bare or wrapped lazy schemas cannot be used as discriminated-union branches because the branch discriminator must be analyzable at construction time.
Code generation annotations
Use the ack_generator builders in
either direction with one annotation, @Schemable(): on a top-level schema it
generates a model, on a class it generates a schema, and on a library;
directive it registers shared custom schemas via @Schemable(schemas: [...]).
package:ack/ack.dart exports @Schemable, @AckKey, and the Is…/Has…
rule annotations.
AckSchema is the runtime schema type; there is no @AckSchema() annotation.
After adding a part '<file>.g.dart'; directive, run:
dart run build_runner build@Schemable() on a top-level schema
Target: Schema variables and getters
Generates: An immutable model class backed by the existing schema
Annotate a top-level schema variable or getter. The schema stays in your source file and remains responsible for validation and codecs.
Supported schema types:
Ack.object({...})→ immutable object models- Primitives:
Ack.string(),Ack.integer(),Ack.double(),Ack.boolean() - Collections:
Ack.list(...),Ack.map(...)fields, and codec-backed sets and maps - JSON values:
Ack.any()fields asObject/Object? - Enums:
Ack.literal(),Ack.enumString(),Ack.enumValues() - Discriminated unions:
Ack.discriminated(...)
Unsupported: nullable roots, one-way transforms, Ack.any() and
Ack.map() roots, Ack.anyOf(), bare Ack.instance<T>(), and anonymous
inline objects
name sets the exact model class name; the class-only options are rejected
here. For Ack.discriminated(...) constraints, see
Model Code Generation.
Example:
import 'package:ack/ack.dart';
part 'user.g.dart';
@Schemable()
final userSchema = Ack.object({
'name': Ack.string(),
'email': Ack.string().email(),
});
// Generated:
// - final class User { ... }
// - The schema variable remains unchanged
// Usage:
final user = User.parse({'name': 'Alice', 'email': 'alice@example.com'});
print(user.name); // Type-safe String access
print(user.email); // Type-safe String access
print(user.toJson());@Schemable() on a class
Concrete models and union branches must be final class declarations with
final stored fields. Annotated sealed union bases remain supported. Parsed
collections and captured extras are recursively unmodifiable; hand-written
constructors remain responsible for defensively copying direct inputs.
Target: Public, constructable classes
Generates: A public <ClassName>Schema facade backed by a private typed
codec (_<className>Schema) and a wireSchema that validates like it but
returns the JSON map, plus the _$ClassAck mixin for toJson, safeToJson,
copyWith, and deep collection-aware == / hashCode / toString
Ack infers schema fields from constructor-backed fields (including Dart 3.13+
primary constructors). Required parameters, nullable types, optional parameters,
JsonMaybe<T>, and constructor defaults determine field presence. Use
caseStyle for model-wide JSON naming and @AckKey(...) on the field
or primary constructor parameter for a wire-name override. Instantiable models
and implicit union branches must apply the generated mixin. In copyWith,
omission keeps the current value and explicit null clears a nullable field.
copyWith returns a typed interface, so a wrongly typed argument is a
compile-time error.
Inferred field types: strings, booleans, numeric types, DateTime, Uri,
Duration, enums, JsonMaybe<T>, nested lists, sets, and string-keyed maps
Rule annotations (from package:ack/ack.dart):
- 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: 4or6for one family) - collections:
@IsNotEmpty,@HasMinItems,@HasMaxItems,@HasUniqueItems
Custom schemas: a field of custom type T resolves through:
@Schemable(schemas: [...])on the class, union base,library;directive, or an importedlibrary;directive;- a static
T.schema/T.schema<A>(...)on the type; - a unique top-level
AckSchema<Boundary, T>variable, getter, or zero-argument function in the current library.
A sealed base annotated with @Schemable(discriminatorKey: ...) generates a discriminated union from its
same-library concrete branches. Unknown properties use
unknownProperties: AckUnknownPropertyPolicy.<policy> (reject by default).
Raw Ack.object(..., additionalProperties: true) schemas preserve extras.
Class projection is a later step: discard is only for tolerant, read-only
consumers, while models that round-trip unknown keys must use capture and may
select the target map with captureField.
import 'package:ack/ack.dart';
part 'account.g.dart';
@Schemable(caseStyle: AckCaseStyle.snake)
final class const Account({
@HasMinLength(2) required final String displayName,
final String role = 'member',
}) with _$AccountAck {
static final schema = AccountSchema.schema;
static final fromJson = AccountSchema.fromJson;
}
final account = Account.schema.parse({'display_name': 'Ada'})!;
print(account.toJson());
print(Account.schema.toJsonSchema());The facade exposes schema, wireSchema, parse, safeParse, fromJson,
encode, safeEncode, toJsonSchema, and toSchemaModel.
static final schema = AccountSchema.schema; attaches the facade’s codec to
Account.schema. The backing codec variable is library-private and no public
lower-camel alias is generated. Set schemaName: 'WireAccountSchema' to choose the exact facade
class name.
Nested class-first fields compose through AddressSchema.schema (or
Address.schema when declared on Address). Imports with combinators can
expose just show Address when Address.schema is declared, or
show Address, AddressSchema otherwise. A schema-first @Schemable()
declaration may also compose the facade explicitly, and class-first models can
use schema-first generated model types on a clean build.
A class-first @Schemable() cannot share a class with @JsonSerializable(),
and name is rejected on a class. Class-first value roots, automatic recursive
graphs, and undiscriminated anyOf shapes
are unsupported; use a schema-first @Schemable() schema and named Ack.lazy for those
cases. See
Model Code Generation for the complete
tutorial and comparison.
EnumSchema<T>
Schema for mapping enum .name strings at the boundary to typed enum values at
runtime. Created using Ack.enumValues(List<T> values) where T extends Enum;
encode and safeEncode map typed enum values back to their names.
AnyOfSchema
Schema for union types; the value must match one of several schemas. Created using Ack.anyOf(List<AckSchema> schemas).
DiscriminatedObjectSchema
Schema for polymorphic validation based on a discriminator field.
- Created using
Ack.discriminated<T extends Object>(...)withdiscriminatorKeyandschemas. effectiveBranch(String discriminatorValue): Returns the branch schema with the discriminator injected as the exact branch literal. Generated subtypes use this to validate a specific branch.
AckSchemaModel
Canonical export model for Ack schemas.
- Created by
schema.toSchemaModel()(preserving imported Draft 2020-12 resources by default) orschema.toSchemaModelDraft7()(lowering imported schemas to Draft-7definitions/$ref). - Represents the boundary/export shape, JSON-compatible defaults, discriminator metadata, target-independent constraints, and export warnings.
schema.toSchemaModel().toJsonSchema()returns the same JSON Schema map asschema.toJsonSchema()(andschema.toSchemaModelDraft7().toJsonSchema()matchesschema.toJsonSchemaDraft7()).- Adapters that need a JSON map should call
schema.toJsonSchema(); adapters for non-JSON targets should convert fromAckSchemaModelrather than traversingAckSchemasubclasses directly.
AnySchema
Accepts any non-null JSON-safe value without further validation.
- Created by
Ack.any(). - Useful for dynamic payloads or pass-through metadata.
- Parsing returns a detached, recursively unmodifiable snapshot of the input; encoding returns the runtime value unchanged after validating it.
MapSchema<ValueBoundary, ValueRuntime>
Schema for a JSON object with arbitrary string keys whose values all match
valueSchema.
- Created by
Ack.map(valueSchema). - Boundary and runtime types are
Map<String, ValueBoundary?>andMap<String, ValueRuntime?>. Nullability is a runtime flag in Ack, so the static value type is nullable; a value isnullonly whenvalueSchemais nullable. - Parse runs
valueSchemaon every value and encode on every non-null value, including codecs; errors report the value’s key path. - Exported to JSON Schema as
{"type": "object", "additionalProperties": <value schema>}.
CodecSchema<Boundary, Runtime>
Schema that decodes boundary values into runtime values and encodes runtime
values back to the boundary representation. Use encode / safeEncode for the
reverse direction. See Codecs.
schema.transform<R>(R Function(Runtime) transformer): one-way transform (parse only;encodefails with a one-way error).schema.codec<R>({required R Function(Runtime) decode, required Runtime Function(R) encode, AckSchema<dynamic, R>? output}): bidirectional codec; the optionaloutputschema validates the runtime value.Ack.codec<Boundary, InputRuntime, Runtime>({required input, required decode, required encode, output}): builds a codec from aninputschema.
Built-in codecs:
Ack.date()→CodecSchema<String, DateTime>(ISOYYYY-MM-DD↔ local-midnightDateTime)Ack.datetime()→CodecSchema<String, DateTime>(ISO 8601 ↔ UTCDateTime; leap-second strings are rejected because Dart cannot represent them)Ack.uri()→CodecSchema<String, Uri>(absolute URI string ↔Uri)Ack.duration()→CodecSchema<int, Duration>(milliseconds ↔Duration)
Optional schemas and JsonMaybe<T>
Every schema can be marked optional via the optional({bool value = true}) fluent API.
schema.optional()setsisOptionaltotruewithout wrapping the schema.schema.optional(value: false)clears the optional flag.- Optional affects object-field presence only; combine with
.nullable()to also allow explicitnull.
In class-first @Schemable() models, use sealed class JsonMaybe<T> (JsonAbsent<T>, JsonValue<T>) when you need to distinguish an omitted JSON property from an explicit null on both parse and toJson:
const JsonMaybe<T>.absent()(JsonAbsent<T>) — key omitted from JSON.const JsonMaybe<T>.value(T? value)(JsonValue<T>) — key present in JSON (with non-null ornullvalue).const JsonMaybe<T>.nullValue()— shorthand forJsonValue<T>(null).maybe.isAbsent,maybe.isPresent,maybe.valueOrNull.
.schema.json code generation (ack_generator:ack_json_schema)
-
Builder (
build.yaml): Enableack_generator:ack_json_schemaonlib/**/*.schema.jsonto emit<name>.schema.dart(withpart '<name>.schema.g.dart';), whichack_generator:ack_generatorcompiles into typed@Schemable()models or validated value models. -
Programmatic API (
package:ack_generator/ack_generator.dart):generateAckSchemaLibraryreturns anAckJsonSchemaLibrarycontainingsource,effectiveDocument, andwidenedPointers. All parameters are named:AckJsonSchemaLibrary generateAckSchemaLibrary({ required Object? document, required Uri documentUri, required String partStem, AckJsonSchemaLibraryOptions options = const AckJsonSchemaLibraryOptions(), Map<Uri, Object> documents = const {}, bool includeParts = true, Version? languageVersion, })Set format assertion through
AckJsonSchemaLibraryOptions(assertFormats: true).
See the Schema types and What’s New & Migration Guide for detailed usage and migration tables.