### Add dart_mappable Dependencies Source: https://pub.dev/documentation/dart_mappable/latest/index Installs the dart_mappable package, along with build_runner and dart_mappable_builder as development dependencies. These are required for code generation. ```bash flutter pub add dart_mappable flutter pub add build_runner --dev flutter pub add dart_mappable_builder --dev ``` -------------------------------- ### Initializing Mappers and Generic Decoding Example Source: https://pub.dev/documentation/dart_mappable/latest/topics/Generics-topic Example demonstrating how to initialize necessary mappers using `ensureInitialized()` and then perform generic decoding with `MapperContainer.globals.fromJson()`. It also shows a case where decoding fails due to uninitialized mappers. ```dart void initMappers() { PersonMapper.ensureInitialized(); CarMapper.ensureInitialized(); } void main() { // Init all required mappers. initMappers(); // You can now call this anywhere. MapperContainer.globals.fromJson('{}'); // Assuming Person model exists // This won't work, since `ensureInitialize()` wasn't called on `AnimalMapper`. // MapperContainer.globals.fromJson('{}'); // Assuming Animal model exists } ``` -------------------------------- ### Custom Build Extensions in build.yaml Source: https://pub.dev/documentation/dart_mappable/latest/topics/Configuration-topic Provides an example of configuring custom build extensions in build.yaml to control the output paths for generated mapper and init files. ```yaml targets: $default: builders: # only to resolve build_runner conflicts dart_mappable_builder: options: build_extensions: 'lib/{{path}}/{{file}}.dart': - 'lib/{{path}}/generated/{{file}}.mapper.dart' - 'lib/{{path}}/generated/{{file}}.init.dart' ``` -------------------------------- ### Working with MapperContainers and Linking - Dart Source: https://pub.dev/documentation/dart_mappable/latest/topics/Mapper%20Container-topic Demonstrates creating and managing custom MapperContainers, including adding mappers, linking containers, and resolving mappers across linked containers. This example highlights how 'MapperContainer.globals' and custom containers interact, and the one-directional nature of linking. ```dart class A {} class B {} class AMapper extends MapperBase {} class BMapper extends MapperBase {} void main() { AMapper.ensureInitialized(); // succeeds - AMapper was added to the globals container. MapperContainer.globals.toJson(A()); // fails - B is not initialized yet. MapperContainer.globals.toJson(A()); BMapper.ensureInitialized(); // creates a new empty container var containerX = MapperContainer(); // fails - no mappers were added yet containerX.toJson(A()); // succeeds - added the respective mapper containerX.use(AMapper()); containerX.toJson(A()); var containerY = MapperContainer(); containerY.use(BMapper()); // succeeds - added the respective mapper containerY.toJson(B()); // fails - missing mapper for type A containerY.toJson(A()); // links containerX to containerY containerY.link(containerX); // succeeds - mapper is resolved through linked containerX containerY.toJson(A()); // fails - linking is one-directional containerX.toJson(B()); } ``` -------------------------------- ### Dart Mappable: Constructor-Based JSON Mapping Examples Source: https://pub.dev/documentation/dart_mappable/latest/topics/Models-topic Demonstrates various custom JSON mapping scenarios in Dart using constructor arguments with the 'dart_mappable' package. Covers default values, ignored fields, renamed fields, and computed values. Note: Matching getters are required for reverse computation. ```dart @MappableClass() class Person with PersonMappable { String name; int age; // basic example, nothing special going on Person.base(this.name, this.age); // setting default values for some parameters Person.opt(this.name, [this.age = 18]); // renamed argument, will be {"years": ...} in json Person.renamed(this.name, int years) : age = years; // ignores the age field completely Person.ignored(this.name); // computed name value Person.computed(String firstName, String lastName, this.age) : name = '$firstName $lastName'; // IMPORTANT: have matching getters for all unassigned arguments, reversing the computed value (*) String get firstName => name.split(' ')[0]; String get lastName => name.split(' ')[1]; } ``` -------------------------------- ### Dart Object Hashing Example Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperEqualityMixin/hash This Dart code demonstrates how to create a hash code for a custom object. It defines an `operator ==` for equality comparison and a `hashCode` getter that uses `Object.hash` to combine the hash codes of its properties. ```dart class SomeObject { final Object a, b, c; SomeObject(this.a, this.b, this.c); bool operator ==(Object other) => other is SomeObject && a == other.a && b == other.b && c == other.c; int get hashCode => Object.hash(a, b, c); } ``` -------------------------------- ### Define a Person Model with dart_mappable Source: https://pub.dev/documentation/dart_mappable/latest/topics/Models-topic This Dart code defines a typical model class 'Person' using the dart_mappable library. It includes required fields and optional deserialization methods. This example demonstrates the basic setup for using dart_mappable. ```dart // This file is "model.dart" import 'package:dart_mappable/dart_mappable.dart'; // required: associates our `models.dart` with the code generated by dart_mappable part 'model.mapper.dart'; @MappableClass() class Person with PersonMappable { const Person({ required this.firstName, required this.lastName, required this.age, }); final String firstName; final String lastName; final int age; // optional: links deserialization factories from the generated [PersonMapper] class static final fromMap = PersonMapper.fromMap; static final fromJson = PersonMapper.fromJson; } ``` -------------------------------- ### RecordCopyWithBase Class Overview Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/RecordCopyWithBase-class Provides an overview of the RecordCopyWithBase class, detailing its inheritance, implemented types, constructors, properties, methods, and operators. ```APIDOC ## RecordCopyWithBase class abstract ### Description An abstract class that provides base functionality for creating copy-with functionality for Record types. It manages the original value and transformation functions to produce a new result. ### Inheritance * Object * CopyWithBase * RecordCopyWithBase ### Implemented Types * RecordCopyWith ### Constructors #### RecordCopyWithBase(T $value, Then $then1, Then $then2) * **$value** (T) - The initial record value. * **$then1** (Then) - A transformation function for the record value. * **$then2** (Then) - A transformation function to produce the final result. ### Properties #### $mapper → RecordMapperBase * **Description**: A mapper specific to Record types. * **Setter**: no setter #### $then1 → Then * **Description**: Inherited transformation function for the record value. * **Final**: true * **Inherited**: true #### $then2 → Then * **Description**: Inherited transformation function to produce the final result. * **Final**: true * **Inherited**: true #### $value → T * **Description**: Inherited initial record value. * **Final**: true * **Inherited**: true #### hashCode → int * **Description**: The hash code for this object. * **Setter**: no setter * **Inherited**: true #### runtimeType → Type * **Description**: A representation of the runtime type of the object. * **Setter**: no setter * **Inherited**: true ### Methods #### $apply(CopyWithData data) → Result * **Description**: Applies copy-with data to produce a result. #### $delta(Map delta) → Result * **Description**: Creates a new result based on a map of changes. * **Override**: true #### $make(CopyWithData data) → T * **Description**: Creates a new instance of the record value with provided data. #### $merge(T value) → Result * **Description**: Merges a new value into the current result. * **Override**: true #### $then(T value) → Result * **Description**: Applies a transformation to the value. * **Inherited**: true #### $update(Then transform) → Result * **Description**: Applies a transformer function on the value. * **Inherited**: true #### as< $C>( $C copy(T, Then , Then )) → $C * **Description**: Converts the current object to another type using a provided copy function. * **Inherited**: true #### noSuchMethod(Invocation invocation) → dynamic * **Description**: Invoked when a nonexistent method or property is accessed. * **Inherited**: true #### or(Object? v, T t) → T * **Description**: Provides a fallback value if the current value is null or invalid. * **Inherited**: true #### toString() → String * **Description**: Returns a string representation of this object. * **Inherited**: true ### Operators #### operator ==(Object other) → bool * **Description**: The equality operator. Compares this object with another object for equality. * **Inherited**: true ``` -------------------------------- ### Dart Polymorphic Classes Example Source: https://pub.dev/documentation/dart_mappable/latest/topics/Polymorphism-topic Defines abstract `Animal` class and concrete `Cat` and `Dog` subclasses. The `Home` class demonstrates holding a polymorphic `Animal` type. This setup is foundational for polymorphic serialization. ```dart abstract class Animal { String name; Animal(this.name); } class Cat extends Animal { String color; Cat(String name, this.color) : super(name); } class Dog extends Animal { int age; Dog(String name, this.age) : super(name); } class Home { Animal pet; Home(this.pet); } ``` -------------------------------- ### Generate Mappers with build_runner Source: https://pub.dev/documentation/dart_mappable/latest/index Command to initiate the code generation process for dart_mappable. This command creates the necessary mapper files based on annotated classes. ```bash dart run build_runner build ``` -------------------------------- ### Global Configuration Options in build.yaml Source: https://pub.dev/documentation/dart_mappable/latest/topics/Configuration-topic Shows how to set global configuration options for dart_mappable in the build.yaml file. This includes case styles, null handling, discriminator keys, and generation methods. ```yaml global_options: dart_mappable_builder: options: # the case style for the map keys, defaults to 'none' caseStyle: none # or 'camelCase', 'snakeCase', etc. # the case style for stringified enum values, defaults to 'none' enumCaseStyle: none # or 'camelCase', 'snakeCase', etc. # if true removes all map keys with null values ignoreNull: false # or true # used as property name for type discriminators discriminatorKey: type # used to specify which methods to generate (all by default) generateMethods: [decode, encode, copy, stringify, equals] ``` -------------------------------- ### Get Mapper for Type T from MapperContainer Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperContainer-class Retrieves the specific MapperBase for a given type T from the container. Returns null if no mapper is found for the requested type. ```dart get([Type? type]) → MapperBase? ``` -------------------------------- ### MapperBase Class Overview Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperBase-class Provides an overview of the abstract MapperBase class, its purpose, and its key components. ```APIDOC ## Abstract Class: MapperBase ### Description The common superclass for all mappers. Subclasses can choose to override a mapping method. It defaults to throwing unsupported exceptions for all methods. ### Implementers * InterfaceMapperBase * IterableMapper * MapMapper * MapperEqualityMixin * PrimitiveMapper * PrimitiveMethodsMixin * SerializableMapper * SimpleMapper * SimpleMapper1Bounded * SimpleMapper2Bounded ### Constructors #### MapperBase() - **Description**: Default constructor for MapperBase. - **Syntax**: `MapperBase()` ### Properties #### hashCode → int - **Description**: The hash code for this object. - **Getter**: Yes - **Setter**: No (inherited) #### id → String - **Description**: A unique id for this type, defaults to the name of the type. - **Getter**: Yes - **Setter**: No #### runtimeType → Type - **Description**: A representation of the runtime type of the object. - **Getter**: Yes - **Setter**: No (inherited) #### type → Type - **Description**: A getter for the type of this mapper. - **Getter**: Yes - **Setter**: No #### typeFactory → Function - **Description**: A type factory is what makes generic types work. - **Getter**: Yes - **Setter**: No ### Methods #### decoder(Object value, DecodingContext context) → T - **Description**: The mapping method to decode `value` to an instance of this mappers type. - **Parameters**: - `value` (Object) - The value to decode. - `context` (DecodingContext) - The decoding context. - **Returns**: An instance of type `T`. #### decodeValue(Object? value, [DecodingOptions? options, MapperContainer? container]) → V - **Description**: Decodes a value, inferring the target type `V`. - **Parameters**: - `value` (Object?) - The value to decode. - `options` (DecodingOptions?, optional) - Decoding options. - `container` (MapperContainer?, optional) - The mapper container. - **Returns**: The decoded value of type `V`. #### encoder(T value, EncodingContext context) → Object? - **Description**: The mapping method to encode `value` to a serializable value. - **Parameters**: - `value` (T) - The value to encode. - `context` (EncodingContext) - The encoding context. - **Returns**: A serializable representation of the value. #### encodeValue(V value, [EncodingOptions? options, MapperContainer? container]) → Object? - **Description**: Encodes a value, inferring the target type `V`. - **Parameters**: - `value` (V) - The value to encode. - `options` (EncodingOptions?, optional) - Encoding options. - `container` (MapperContainer?, optional) - The mapper container. - **Returns**: The encoded value. #### equals(T value, T other, MappingContext context) → bool - **Description**: The mapping method to compare `value` and `other` for equality. - **Parameters**: - `value` (T) - The first value to compare. - `other` (T) - The second value to compare. - `context` (MappingContext) - The mapping context. - **Returns**: `true` if the values are equal, `false` otherwise. #### equalsValue(T value, Object? other, [MapperContainer? container]) → bool - **Description**: Compares a value for equality using an optional mapper container. - **Parameters**: - `value` (T) - The value to compare. - `other` (Object?) - The other object to compare against. - `container` (MapperContainer?, optional) - The mapper container. - **Returns**: `true` if the values are equal, `false` otherwise. #### hash(T value, MappingContext context) → int - **Description**: The mapping method to calculate the hash of `value`. - **Parameters**: - `value` (T) - The value to hash. - `context` (MappingContext) - The mapping context. - **Returns**: The hash code of the value. - **Overrides**: `hash` from `Object`. #### hashValue(T value, [MapperContainer? container]) → int - **Description**: Calculates the hash of a value using an optional mapper container. - **Parameters**: - `value` (T) - The value to hash. - `container` (MapperContainer?, optional) - The mapper container. - **Returns**: The hash code of the value. #### includeTypeId(dynamic v) → bool - **Description**: Checks if a dynamic value includes its type identifier. - **Parameters**: - `v` (dynamic) - The value to check. - **Returns**: `true` if the type ID is included, `false` otherwise. #### isFor(dynamic v) → bool - **Description**: Checks if this mapper is suitable for a given dynamic value. - **Parameters**: - `v` (dynamic) - The value to check. - **Returns**: `true` if the mapper is suitable, `false` otherwise. #### isForType(Type type) → bool - **Description**: Checks if this mapper is suitable for a given static type. - **Parameters**: - `type` (Type) - The type to check. - **Returns**: `true` if the mapper is suitable, `false` otherwise. #### isValueEqual(T value, Object? other, [MapperContainer? container]) → bool - **Description**: Checks if a value is equal to another using an optional mapper container. Similar to `equalsValue` but potentially with different internal logic. - **Parameters**: - `value` (T) - The value to check. - `other` (Object?) - The other object to compare against. - `container` (MapperContainer?, optional) - The mapper container. - **Returns**: `true` if the values are equal, `false` otherwise. #### noSuchMethod(Invocation invocation) → dynamic - **Description**: Invoked when a nonexistent method or property is accessed. Inherited from `Object`. - **Parameters**: - `invocation` (Invocation) - The invocation details. - **Returns**: The result of the nonexistent method or property access. #### stringify(T value, MappingContext context) → String - **Description**: The mapping method to get the string representation of `value`. - **Parameters**: - `value` (T) - The value to stringify. - `context` (MappingContext) - The mapping context. - **Returns**: The string representation of the value. #### stringifyValue(T value, [MapperContainer? container]) → String - **Description**: Gets the string representation of a value using an optional mapper container. - **Parameters**: - `value` (T) - The value to stringify. - `container` (MapperContainer?, optional) - The mapper container. - **Returns**: The string representation of the value. #### toString() → String - **Description**: A string representation of this object. Inherited from `Object`. - **Returns**: The string representation of the object. ### Operators #### operator ==(Object other) → bool - **Description**: The equality operator. Compares this object with another object for equality. Inherited from `Object`. - **Parameters**: - `other` (Object) - The object to compare with. - **Returns**: `true` if the objects are equal, `false` otherwise. ### Static Methods #### addType([Function? factory]) → void - **Description**: Registers an additional type `T` to be identifiable by the package. An optional factory function can be provided. - **Type Parameters**: - `` - The type to register. - **Parameters**: - `factory` (Function?, optional) - A factory function for the type `T`. #### checkStaticType(dynamic v) → bool - **Description**: Checks if the static type `V` matches the dynamic runtime type of `v`. - **Type Parameters**: - `` - The static type to check against. - **Parameters**: - `v` (dynamic) - The dynamic value whose type to check. - **Returns**: `true` if the static type matches the runtime type, `false` otherwise. ``` -------------------------------- ### Get Global MapperContainer Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperContainer-class Provides access to the global MapperContainer, which holds all globally registered mappers. This allows for centralized management of mappers across the application. ```dart static MapperContainer get globals → MapperContainer ``` -------------------------------- ### Get Default MapperContainer Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperContainer-class Provides access to the default MapperContainer, which is pre-populated with mappers for core Dart types like primitives, List, Set, Map, and DateTime. ```dart static MapperContainer get defaults → MapperContainer ``` -------------------------------- ### CopyWithData Class Overview Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/CopyWithData-class Provides a detailed look at the CopyWithData abstract class, including its constructors, properties, and methods. ```APIDOC ## CopyWithData Class ### Description The `CopyWithData` class is an abstract class that defines a common interface for data copying operations. It serves as a base for various specific data copying strategies. ### Implementers - DeltaCopyWithData - FieldCopyWithData - MergeCopyWithData - RecordDeltaCopyWithData - RecordMergeCopyWithData ### Constructors #### `CopyWithData()` - **Description**: The default constructor for the `CopyWithData` class. ### Properties #### `hashCode` → `int` - **Description**: An integer representing the hash code of the object. This property is inherited and has no setter. #### `runtimeType` → `Type` - **Description**: A `Type` object representing the runtime type of the object. This property is inherited and has no setter. ### Methods #### `get(Symbol name, {Object? or})` → `V` - **Description**: Retrieves a value associated with the given `name` symbol. An optional `or` value can be provided as a fallback. #### `noSuchMethod(Invocation invocation)` → `dynamic` - **Description**: Invoked when a nonexistent method or property is accessed. This method is inherited. #### `toString()` → `String` - **Description**: Returns a string representation of the object. This method is inherited. ### Operators #### `operator ==(Object other)` → `bool` - **Description**: Compares the equality of this object with another object. This operator is inherited. ``` -------------------------------- ### Dart toString Method Implementation for Debugging Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperException/toString Demonstrates how to override the toString method in Dart to provide a custom string representation of an object, primarily for debugging or logging purposes. This example shows a typical override for a custom exception class. ```dart @override String toString() => 'MapperException: $message'; ``` -------------------------------- ### EmptyToNullHook Class Documentation Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/EmptyToNullHook-class Provides detailed documentation for the EmptyToNullHook class, including its methods and properties. ```APIDOC ## Class: EmptyToNullHook ### Description A `MappingHook` that converts an empty string to `null` during the mapping process. ### Inheritance - `Object` - `MappingHook` - `EmptyToNullHook` ### Constructors #### `EmptyToNullHook()` Creates a new instance of the `EmptyToNullHook` class. ### Properties #### `hashCode` → `int` The hash code for this object. (Inherited from `Object`) #### `runtimeType` → `Type` A representation of the runtime type of the object. (Inherited from `Object`) ### Methods #### `afterDecode(dynamic value)` → `dynamic` Receives the decoded value after decoding. (Overrides `MappingHook.afterDecode`) #### `afterEncode(Object? value)` → `Object?` Receives the encoded value after encoding. (Inherited from `MappingHook.afterEncode`) #### `beforeDecode(Object? value)` → `Object?` Receives the encoded value before decoding. (Inherited from `MappingHook.beforeDecode`) #### `beforeEncode(Object? value)` → `Object?` Receives the decoded value before encoding. This is where the empty string to null conversion likely occurs. (Inherited from `MappingHook.beforeEncode`) #### `noSuchMethod(Invocation invocation)` → `dynamic` Invoked when a nonexistent method or property is accessed. (Inherited from `Object.noSuchMethod`) #### `toString()` → `String` A string representation of this object. (Inherited from `Object.toString`) ### Operators #### `operator ==(Object other)` → `bool` The equality operator. (Inherited from `Object.operator==`) ``` -------------------------------- ### ClassCopyWithBase Constructor and Properties Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/ClassCopyWithBase-class This snippet shows the constructor and properties of the abstract ClassCopyWithBase. It takes an initial value, two transformation functions, and a mapper. Properties include the mapper, transformation functions, the initial value, and inherited properties like hashCode, runtimeType, and operators. ```dart abstract class ClassCopyWithBase { ClassCopyWithBase(In $value, Then $then1, Then $then2); final ClassMapperBase $mapper; final Then $then1; final Then $then2; final In $value; int get hashCode => super.hashCode; Type get runtimeType => super.runtimeType; } ``` -------------------------------- ### MappableLib Configuration Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MappableLib-class This section details the constructor and properties of the MappableLib class, which are used to set default configurations for mappable libraries. ```APIDOC ## MappableLib Constructor and Properties ### Description Used to annotate a library to define default values for mappable configurations. ### Constructor `MappableLib({CaseStyle? caseStyle, CaseStyle? enumCaseStyle, bool? ignoreNull, String? discriminatorKey, int? generateMethods, InitializerScope? generateInitializerForScope})` ### Properties - **caseStyle** (CaseStyle?) - The case style for the map keys. - **discriminatorKey** (String?) - Property key used for type discriminators. - **enumCaseStyle** (CaseStyle?) - The case style for the stringified enum values. - **ignoreNull** (bool?) - If true, removes all map keys with null values. - **generateMethods** (int?) - Specify which methods to generate for classes. - **generateInitializerForScope** (InitializerScope?) - Will generate a new `.init.dart` file with an initializer method that automatically registers all mappers in the scope. ``` -------------------------------- ### Registering Custom Iterable and Map Mappers in Dart Source: https://pub.dev/documentation/dart_mappable/latest/topics/Custom%20Mappers-topic Demonstrates how to register custom IterableMapper and MapMapper for HashSet and HashMap types. It shows how to initialize these mappers with factory functions and type factories. The example also includes a basic usage scenario converting a JSON string list to a HashSet. ```dart void main() { MapperContainer.globals.use(IterableMapper( (Iterable i) => HashSet.of(i), (f) => f>(), )); MapperContainer.globals.use(MapMapper( (Map m) => HashMap.of(m), (f) => f>(), )); HashSet brands = MapperContainer.globals.fromJson('["Toyota", "Audi", "Audi"]'); print(brands); // Note: The original print statement was 'print(String);', corrected to 'print(brands);' for clarity. } ``` -------------------------------- ### Generating Initializer with @MappableLib Annotation Source: https://pub.dev/documentation/dart_mappable/latest/topics/Generics-topic Demonstrates using the `@MappableLib` annotation with `generateInitializerForScope` to automatically generate an initializer function for mappers. This reduces boilerplate code for setting up mappers in a project. ```dart @MappableLib(generateInitializerForScope: InitializerScope.package) library main; // This annotation will trigger the generation of an initializeMappers() function // in a separate .init.dart file, based on the specified scope. ``` -------------------------------- ### MappableConstructor Class Overview Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MappableConstructor-class This section provides an overview of the MappableConstructor class, including its purpose, constructors, properties, methods, and operators. ```APIDOC ## MappableConstructor Class ### Description Used to annotate a constructor to be chosen as the serialization function. ### Constructors #### MappableConstructor() - **Type**: const - **Description**: Creates a new MappableConstructor instance. ### Properties #### hashCode → int - **Type**: int - **Description**: The hash code for this object. (inherited) #### runtimeType → Type - **Type**: Type - **Description**: A representation of the runtime type of the object. (inherited) ### Methods #### noSuchMethod(Invocation invocation) → dynamic - **Type**: dynamic - **Description**: Invoked when a nonexistent method or property is accessed. (inherited) #### toString() → String - **Type**: String - **Description**: A string representation of this object. (inherited) ### Operators #### operator ==(Object other) → bool - **Type**: bool - **Description**: The equality operator. (inherited) ``` -------------------------------- ### Dart Mappable Integration with Freezed Union Source: https://pub.dev/documentation/dart_mappable/latest/topics/Migration%20and%20Compatibility-topic This example demonstrates how to make a Freezed union class compatible with `dart_mappable`. It involves adding `@MappableClass` and `@MappableField` annotations to the Freezed class and its factory constructors. This allows `dart_mappable` to correctly serialize and deserialize the union type, using `discriminatorKey` and `discriminatorValue` for polymorphism. ```dart part 'myfile.freezed.dart'; part 'myfile.mapper.dart'; @freezed @MappableClass(discriminatorKey: 'type') class Union with _$Union { @MappableClass(discriminatorValue: 'data') const factory Union.data(@MappableField(key: 'mykey') int value) = Data; @MappableClass(discriminatorValue: 'loading') const factory Union.loading() = Loading; @MappableClass(discriminatorValue: 'error') const factory Union.error([String? message]) = ErrorDetails; } ``` -------------------------------- ### Using Dart Mappable with Freezed Union Source: https://pub.dev/documentation/dart_mappable/latest/topics/Migration%20and%20Compatibility-topic This Dart code snippet shows how to instantiate a Freezed union class after it has been made compatible with `dart_mappable`. It demonstrates serializing an instance to JSON and then deserializing it back using the generated `UnionMapper`. This highlights the practical application of the integration. ```dart void main() { var data = Union.data(42); var dataJson = data.toJson(); print(dataJson); // {"mykey":42,"type":"data"} var parsedData = UnionMapper.fromJson(dataJson); print(parsedData); // Union.data(value: 42) } ``` -------------------------------- ### Modify Input JSON Before Decoding with a Custom Hook Source: https://pub.dev/documentation/dart_mappable/latest/topics/Mapping%20Hooks-topic Shows a practical example of using a `MappingHook`'s `beforeDecode` method to transform incoming JSON data. This hook handles cases where a field might be a string (representing an ID) instead of a full JSON object, converting it into the expected object format before decoding. ```dart class PlayerHook extends MappingHook { const PlayerHook(); @override Object? beforeDecode(Object? value) { if (value is String) { return {'id': value}; } return value; } } // Example usage in main function: // Game game = GameMapper.fromJson('{"player": {"id": "Tom"}}'); // print(game.player.id); // Tom; // Game game2 = GameMapper.fromJson('{"player": "John"}'); // print(game2.player.id); // John ``` -------------------------------- ### MappableField Class Documentation Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MappableField-class Provides details on the MappableField class, its constructors, properties, methods, and operators. ```APIDOC ## MappableField Class ### Description Used to annotate a parameter or field to overwrite the mapped key. ### Constructors #### MappableField({String? key, MappingHook? hook}) **Parameters:** - **key** (String?) - Optional - Use this key instead of the field name. - **hook** (MappingHook?) - Optional - Define custom hooks used only for this field. ### Properties - **hashCode** (int) - The hash code for this object. - **hook** (MappingHook?) - Define custom hooks used only for this field. - **key** (String?) - Use this key instead of the field name. - **runtimeType** (Type) - A representation of the runtime type of the object. ### Methods - **noSuchMethod(Invocation invocation)** (dynamic) - Invoked when a nonexistent method or property is accessed. - **toString()** (String) - A string representation of this object. ### Operators - **operator ==(Object other)** (bool) - The equality operator. ``` -------------------------------- ### DeltaCopyWithData Class Details Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/DeltaCopyWithData-class Provides detailed information about the DeltaCopyWithData class, including its constructors, properties, methods, and inheritance hierarchy. ```APIDOC ## DeltaCopyWithData Class ### Description Represents a data class with delta copy-with functionality, inheriting from CopyWithData and ultimately Object. It holds a mapper and a map of values. ### Inheritance * Object * CopyWithData * DeltaCopyWithData ### Constructors #### `DeltaCopyWithData(ClassMapperBase mapper, Map value)` Initializes a new instance of the `DeltaCopyWithData` class. ### Properties * **`context`** (DecodingContext) - `final` The decoding context associated with this instance. * **`hashCode`** (int) - `inherited` The hash code for this object. No setter available. * **`mapper`** (ClassMapperBase) - `final` The class mapper used for data transformation. * **`runtimeType`** (Type) - `inherited` A representation of the runtime type of the object. No setter available. * **`value`** (Map) - `final` The map containing the data values. ### Methods #### `get(Symbol name, {Object? or = $none})` → V Retrieves a value by its symbol name, with an optional default value. #### `noSuchMethod(Invocation invocation)` → dynamic `inherited` Invoked when a nonexistent method or property is accessed. #### `toString()` → String `inherited` A string representation of this object. ### Operators #### `operator ==(Object other)` → bool `inherited` The equality operator. ``` -------------------------------- ### InterfaceMapperBase Overview Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/InterfaceMapperBase-class This section provides an overview of the InterfaceMapperBase class, its inheritance, and implementers. ```APIDOC ## InterfaceMapperBase class The common mapper interface for class and record mappers. ### Inheritance * Object * MapperBase * InterfaceMapperBase ### Implementers * ClassMapperBase * RecordMapperBase ``` -------------------------------- ### Use Generated Mappers and Mixins Source: https://pub.dev/documentation/dart_mappable/latest/index Illustrates how to use the generated mappers and mixins provided by dart_mappable for encoding, decoding, comparison, and copying objects. Covers usage of `MyClassMapper`, `toMap`, `toJson`, `fromJson`, `operator ==`, `hashCode`, `toString`, and `copyWith`. ```dart // Decode a [Map] using the [MyClassMapper] class: MyClass myClass = MyClassMapper.fromMap({'myValue': 123}); // Or decode directly from json: MyClass myClass2 = MyClassMapper.fromJson('{"myValue": 123}'); // Encode an instance of your class using the methods provided by the mixin: Map map = myClass.toMap(); String json = myClass.toJson(); // There are also implementations generated for [operator ==], [hashCode] and [toString]: bool thisIsTrue = (myClass == myClass2); print(myClass); // Last you can use [copyWith] to create a copy of an object: MyClass myClass3 = myClass.copyWith(myValue: 0); ``` -------------------------------- ### ClassCopyWithBase Methods Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/ClassCopyWithBase-class This snippet details the methods available in the ClassCopyWithBase abstract class. It includes methods for applying transformations, handling deltas, creating instances, merging values, updating transformers, and utility methods like as, noSuchMethod, or, and toString. ```dart abstract class ClassCopyWithBase { // ... constructors and properties ... Result $apply(CopyWithData data); Result $delta(Map delta); In $make(CopyWithData data); Result $merge(In value); Result $then(In value); Result $update(Then transform); $C as<$C>(CopyWithFunc<$C, In, Then, Then> copy); dynamic noSuchMethod(Invocation invocation); T or(Object? v, T t); String toString(); } ``` -------------------------------- ### InterfaceMapperBase Methods Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/InterfaceMapperBase-class Documentation for the methods available in the InterfaceMapperBase class, including decoding and encoding functionalities. ```APIDOC ## Methods ### `decode(Object? value, DecodingContext context) → T` Decodes a value into an object of type T. ### `decodeJson(String json) → V` Decodes a JSON string into an object of type V. ### `decodeMap(Map map) → V` Decodes a map into an object of type V. ### `decoder(Object? value, DecodingContext context) → T` The mapping method to decode `value` to an instance of this mappers type. ### `decodeValue(Object? value, [DecodingOptions? options, MapperContainer? container]) → V` Decodes a value with optional decoding options and a mapper container. ### `encode(T value, EncodingContext context) → Object?` Encodes an object of type T into a serializable format. ### `encodeJson(V object, [EncodingOptions? options]) → String` Encodes an object into a JSON string. ### `encodeMap(V object, [EncodingOptions? options]) → Map` Encodes an object into a map. ### `encoder(T value, EncodingContext context) → Object?` The mapping method to encode `value` to a serializable value. ### `encodeValue(V value, [EncodingOptions? options, MapperContainer? container]) → Object?` Encodes a value with optional encoding options and a mapper container. ### `equals(T value, T other, MappingContext context) → bool` The mapping method to compare `value` and `other` for equality. ### `equalsValue(T value, Object? other, [MapperContainer? container]) → bool` Compares two values for equality with an optional mapper container. ### `hash(T value, MappingContext context) → int` The mapping method to calculate the hash of `value`. ### `hashValue(T value, [MapperContainer? container]) → int` Calculates the hash of a value with an optional mapper container. ### `includeTypeId(dynamic v) → bool` Checks if type ID should be included. ### `isFor(dynamic v) → bool` Checks if the mapper is for the given value. ### `isForType(Type type) → bool` Checks if the mapper is for the given type. ### `isValueEqual(T value, Object? other, [MapperContainer? container]) → bool` Checks if the value is equal to another value with an optional mapper container. ### `noSuchMethod(Invocation invocation) → dynamic` Invoked when a nonexistent method or property is accessed. ### `stringify(T value, MappingContext context) → String` The mapping method to get the string representation of `value`. ### `stringifyValue(T value, [MapperContainer? container]) → String` Gets the string representation of a value with an optional mapper container. ``` -------------------------------- ### InterfaceMapperBase Static Methods Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/InterfaceMapperBase-class Documentation for static methods available in the InterfaceMapperBase class. ```APIDOC ## Static Methods ### `encodeFields(T value, Iterable> fields, bool ignoreNull, EncodingContext context, bool shallow) → Map` Encodes fields of an object into a map. ``` -------------------------------- ### Dart Mappable: Hash Method Implementation Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MapperEqualityMixin/hash This snippet shows the implementation of the `hash` method in Dart Mappable. It utilizes the `equality` function and `MapperEquality` with a `MappingContext` to compute the hash code for a given value. ```dart @override int hash(T value, MappingContext context) => equality(MapperEquality(context.container)).hash(value); ``` -------------------------------- ### Annotate Class for dart_mappable Source: https://pub.dev/documentation/dart_mappable/latest/index Demonstrates how to annotate a Dart class with `@MappableClass()` and include the generated mapper file. This is the first step in enabling dart_mappable functionality for a class. ```dart // This file is "model.dart" import 'package:dart_mappable/dart_mappable.dart'; // Will be generated by dart_mappable part 'model.mapper.dart'; @MappableClass() class MyClass with MyClassMappable { final int myValue; MyClass(this.myValue); } ``` -------------------------------- ### Dart Field Constructor Implementation Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/Field/Field Shows the implementation of the 'Field' constructor in Dart. It initializes instance variables, with 'key' defaulting to 'name' if not provided. ```dart const Field( this.name, this.getter, { String? key, this.mode = FieldMode.field, this.arg, this.opt = false, this.def, this.hook, this.data, }) : key = key ?? name; ``` -------------------------------- ### EncodingOptions Class Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/EncodingOptions-class This section details the EncodingOptions class, its constructor, properties, and methods. ```APIDOC ## Class: EncodingOptions ### Description Additional options to be passed to `MapperContainer.toValue`. This class allows for customization of type inclusion, inheritance, and shallow encoding. ### Constructor #### `EncodingOptions({bool? includeTypeId, bool inheritOptions = true, bool? shallow, Object? data})` Creates a new instance of `EncodingOptions`. - **includeTypeId** (bool?) - Optional. Whether to include the type ID of the encoding object. - **inheritOptions** (bool) - Optional. Defaults to `true`. Whether to inherit these options for nested calls. - **shallow** (bool?) - Optional. Whether to encode nested objects or just one level deep. - **data** (Object?) - Optional. Custom data object passed to the mapper. ### Properties - **data** (Object?) - Custom data object passed to the mapper. - **hashCode** (int) - The hash code for this object. - **includeTypeId** (bool?) - Whether to include the type ID of the encoding object. - **inheritOptions** (bool) - Whether to inherit these options for nested calls to `MapperContainer.toValue`, like for encoding fields of a class. - **runtimeType** (Type) - A representation of the runtime type of the object. - **shallow** (bool?) - Whether to encode nested objects or just one level deep. ### Methods - **copyWith({Object? data}) → EncodingOptions** Creates a copy of the `EncodingOptions` with optional updated fields. - **noSuchMethod(Invocation invocation) → dynamic** Invoked when a nonexistent method or property is accessed. - **toString() → String** A string representation of this object. ### Operators - **operator ==(Object other) → bool** The equality operator. Checks if two `EncodingOptions` objects are equal. ``` -------------------------------- ### MappingHook Class Overview Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/MappingHook-class Provides an overview of the MappingHook class, its purpose, and how to extend it for custom mapping. ```APIDOC ## MappingHook Class ### Description Abstract class for defining custom mapping hooks for classes or fields. Implementers can create specialized mapping logic. ### Implementers * ChainedHook * EmptyToNullHook * UnescapeNewlinesHook * UnmappedPropertiesHook ### Constructors #### `MappingHook()` * **Description**: Default constructor for MappingHook. * **Type**: `const` ### Properties #### `hashCode` → `int` * **Description**: The hash code for this object. * **Setter**: `no setter` (inherited) #### `runtimeType` → `Type` * **Description**: A representation of the runtime type of the object. * **Setter**: `no setter` (inherited) ### Methods #### `afterDecode(Object? value) → Object?` * **Description**: Receives the decoded value after decoding. #### `afterEncode(Object? value) → Object?` * **Description**: Receives the encoded value after encoding. #### `beforeDecode(Object? value) → Object?` * **Description**: Receives the encoded value before decoding. #### `beforeEncode(Object? value) → Object?` * **Description**: Receives the decoded value before encoding. #### `noSuchMethod(Invocation invocation) → dynamic` * **Description**: Invoked when a nonexistent method or property is accessed. * **Inheritance**: `inherited` #### `toString() → String` * **Description**: A string representation of this object. * **Inheritance**: `inherited` ### Operators #### `operator ==(Object other) → bool` * **Description**: The equality operator. * **Inheritance**: `inherited` ``` -------------------------------- ### Extensions Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable Provides extensions to add utility methods for case style transformation, chained copyWith operations, and mapping context calls. ```APIDOC ## Extensions ### CaseStyleTransform on CaseStyle? ### ChainedCopyWith on ObjectCopyWith ### MappingContextCall on O Utility methods to call a generic function with the type argument of the mapping context. ### TextTransformer on TextTransform? ### TextTransformParser on TextTransform ``` -------------------------------- ### Ensure Generator Order for Compatibility with other Packages (build.yaml) Source: https://pub.dev/documentation/dart_mappable/latest/topics/Migration%20and%20Compatibility-topic This configuration in `build.yaml` ensures that the `dart_mappable` code generator runs before other code generators, such as `retrofit_generator` or `chopper_generator`. This is crucial when your data classes need to be compatible with packages that rely on `json_serializable`'s method signatures. ```yaml global_options: dart_mappable_builder: runs_before: # list the generator packages you depend on, e.g. - retrofit_generator - chopper_generator options: # ... other dart_mappable options, including 'renameMethods' ``` -------------------------------- ### DecodingContext Methods Source: https://pub.dev/documentation/dart_mappable/latest/dart_mappable/DecodingContext-class Lists the methods available on the DecodingContext, such as arg, callWith variants, change, inherit, noSuchMethod, toString, and type. ```dart arg(int index, [List argIndices = const []]) → Type callWith(Function fn, U value) → R callWith1(R fn(U), [U? value]) → R callWith2(R fn(U), [U? value]) → R callWith3(R fn(U), [U? value]) → R change({MapperContainer? container, List args()?, bool? inherited}) → DecodingContext inherit({MapperContainer? container, List args()?}) → DecodingContext noSuchMethod(Invocation invocation) → dynamic type(Function factory, [List args = const []]) → Type ```