API Reference
This page provides a quick reference for the core Ack classes, methods, and annotations. For detailed explanations and usage examples, refer to the specific guides linked below.
Core Ack
Class
Entry point for creating schemas. See Schema Validation.
Ack.string()
: Creates aStringSchema
for validating strings.Ack.integer()
: Creates anIntegerSchema
for validating integers.Ack.double()
: Creates aDoubleSchema
for validating floating-point numbers.Ack.boolean()
: Creates aBooleanSchema
for validating booleans.Ack.list(AckSchema itemSchema)
: Creates aListSchema
for validating arrays.Ack.object(Map<String, AckSchema> properties)
: Creates anObjectSchema
for validating objects.Ack.enumValues(List<T> values)
: Creates anEnumSchema
for validating enum values.Ack.enumString(List<String> values)
: Creates a string schema that only accepts specific values.Ack.anyOf(List<AckSchema> schemas)
: Creates anAnyOfSchema
for union types.Ack.any()
: Creates anAnySchema
that accepts any value.Ack.discriminated({required String discriminatorKey, required Map<String, AckSchema> schemas})
: Creates a discriminated union schema.
Primary Validation Methods
SchemaResult<T> safeParse(Object? data, {String? debugName})
: Validates the input data and returns a result. Never throws exceptions - returnsSchemaResult
with either success or failure.T? parse(Object? data, {String? debugName})
: Validates the input data and returns the value. ThrowsAckException
if validation fails.T? tryParse(Object? data, {String? debugName})
: Deprecated - UsesafeParse(...).getOrNull()
instead.SchemaResult<T> validate(Object? data, {String? debugName})
: Deprecated - UsesafeParse(...)
instead.
Schema Modification Methods
AckSchema<T> nullable()
: Returns a new schema that also acceptsnull
values.AckSchema<T> optional({bool value = true})
: Returns a new schema marked as optional (for object fields).AckSchema<T> withDescription(String description)
: Adds a description for documentation and JSON Schema generation.AckSchema<T> withDefault(T value)
: Sets a default value when input isnull
.StringSchema strictParsing({bool value = true})
: Enables strict parsing for strings.IntegerSchema strictParsing({bool value = true})
: Enables strict parsing for integers.DoubleSchema strictParsing({bool value = true})
: Enables strict parsing for doubles.BooleanSchema strictParsing({bool value = true})
: Enables strict parsing for booleans.
Custom Validation Methods
AckSchema<T> constrain(Constraint<T> constraint, {String? message})
: Applies a custom validation constraint.AckSchema<T> withConstraint(Constraint<T> constraint)
: Applies a custom validation constraint (alias forconstrain
).AckSchema<T> refine(bool Function(T) validate, {String message})
: Adds custom validation logic with an optional custom error message.TransformedSchema<T, R> transform<R>(R Function(T?) transformer)
: Transforms validated values to a different type.
Utility Methods
Map<String, Object?> toJsonSchema()
: Converts the schema to a JSON Schema Draft-7 representation.Map<String, Object?> toMap()
: Serializes the schema for debugging.
See also Schema Validation 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 regex pattern. Note: Patterns are NOT automatically anchored - use^...$
for full-string matching. See String Validation for details.contains(String pattern, {String? example, String? message})
: Must contain pattern anywhere in string (partial matching)startsWith(String value)
: Must start with specified valueendsWith(String value)
: Must end with specified value
Format Validation
email()
: Must be valid email formaturl()
: Must be valid URL format (alias foruri()
)uri()
: Must be valid URI according to RFC 3986uuid()
: 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 valid ISO 8601 datetimetime()
: Must be valid time format (HH:MM:SS)
Value Restrictions
literal(String value)
: Must exactly match the given valueenumString(List<String> values)
: Must be one of the specified values
Transformations
trim()
: Removes leading and trailing whitespacetoLowerCase()
: Converts to lowercasetoUpperCase()
: Converts to uppercase
IntegerSchema
/ DoubleSchema
(Number Schemas)
Schemas for validating numbers. See Number Validation.
min(num limit)
: Minimum value (inclusive)max(num limit)
: Maximum value (inclusive)positive()
: Must be greater than 0negative()
: Must be less than 0multipleOf(num factor)
: Must be a multiple of the factorfinite()
: Must be finite (DoubleSchema only)safe()
: Must be within safe integer range (IntegerSchema only)
BooleanSchema
Schema for validating booleans. Validates true
and false
values, with optional type coercion from strings and numbers.
ListSchema<T>
Schema for validating arrays. See List Validation.
minLength(int min)
: Minimum number of itemsmaxLength(int max)
: Maximum number of itemslength(int exact)
: Exact number of itemsunique()
: 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 additional properties not defined in the schema.
SchemaResult<T>
Object returned by safeParse()
. See Error Handling.
bool isOk
: True if validation succeededbool isFail
: True if validation failedT getOrThrow()
: Returns the validated value or throws an exceptionT? getOrNull()
: Returns the validated value or null if validation failedSchemaError getError()
: Returns the validation error (only valid whenisFail
is true)T getOrElse(T Function() defaultValue)
: Returns the validated value or a default
SchemaError
(and Subclasses)
Object representing a validation failure. See Error Handling.
String message
: Human-readable error messageSchemaContext context
: Context information about where the error occurred
Subclasses:
SchemaConstraintsError
: Constraint validation failuresSchemaNestedError
: Nested validation failures (for objects/arrays)SchemaValidationError
: Custom refinement failures
Constraint<T>
Base class for creating custom validation rules. See Custom Validation.
ConstraintError? validate(T value)
: Validates a value and returns an error if invalidMap<String, Object?> toMap()
: Serializes the constraint for debugging
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 helpers like Ack.date()
, Ack.literal()
, and rich list/object
combinators.
Code Generation Annotations
Use the ack_generator
builder to
turn annotations into ready-to-use schemas and extension types. After adding
the annotations below, run:
dart run build_runner build
@AckModel()
Target: Dart classes
Generates: Both a schema constant AND an extension type
Annotate a Dart class to automatically generate a validation schema and a strongly typed extension type. The generator analyzes your class fields and creates:
- A schema constant named
<className>Schema
(e.g.,userSchema
) - An extension type named
<ClassName>Type
(e.g.,UserType
)
Parameters:
schemaName
: Custom name for the generated schema constantdescription
: Documentation string for the schemaadditionalProperties
: Allow extra fields not defined in the classadditionalPropertiesField
: Field name to store extra properties (must beMap<String, dynamic>
)discriminatedKey
: Field name for type discrimination (use on abstract base classes)discriminatedValue
: Discriminator value for this subtype (use on concrete implementations)
Example:
@AckModel(description: 'User profile')
class User {
final String name;
final int age;
User({required this.name, required this.age});
}
// Generated:
// - final userSchema = Ack.object({...});
// - extension type UserType(Map<String, Object?> _data) { ... }
// Usage:
final user = UserType.parse({'name': 'Alice', 'age': 30});
print(user.name); // Type-safe String access
@AckType()
Target: Schema variables and getters
Generates: ONLY an extension type (schema must already exist)
Annotate an existing schema variable or getter to generate an extension type wrapper. Unlike @AckModel
, this does not create the schema—it only adds type-safe access to a schema you've already written.
Supported schema types:
Ack.object({...})
→ Object extension types- Primitives:
Ack.string()
,Ack.integer()
,Ack.double()
,Ack.boolean()
- Collections:
Ack.list(...)
- Enums:
Ack.literal()
,Ack.enumString()
,Ack.enumValues()
Unsupported: Ack.any()
, Ack.anyOf()
, Ack.discriminated()
(use @AckModel
for discriminated unions)
Example:
@AckType()
final userSchema = Ack.object({
'name': Ack.string(),
'email': Ack.string().email(),
});
// Generated:
// - extension type UserType(Map<String, Object?> _data) { ... }
// - The schema variable remains unchanged
// Usage:
final user = UserType.parse({'name': 'Alice', 'email': 'alice@example.com'});
print(user.name); // Type-safe String access
print(user.email); // Type-safe String access
EnumSchema<T>
Schema for validating enum values.
- Created using
Ack.enumValues(List<T> values)
where T extends Enum
AnyOfSchema
Schema for union types (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({required String discriminatorKey, required Map<String, AckSchema> schemas})
AnySchema
Schema that accepts any value without validation.
- Created using
Ack.any()
- Useful for gradual migration or maximum flexibility
TransformedSchema<T, R>
Schema that transforms validated values.
- Created using
schema.transform<R>(R Function(T?) transformer)
Optional Schemas
Every schema can be marked optional through the optional({bool value = true})
fluent API.
- Calling
schema.optional()
setsisOptional
totrue
without wrapping the schema. - Use
schema.optional(value: false)
to clear the optional flag. - Optional affects object-field presence only; combine with
.nullable()
to also allow explicitnull
.
Refer to the Schema Validation guide for detailed usage and examples.