Converter class
Allows you to convert the annotated object to the objectType object.
It's works almost like Json parsing, but here we are parsing Dart objects, this can be helpful if your two objects aren't subclasses of a common parent.
// The class which will hold the converting logic. You just annotating it with
// @Convert and pass the type off the class you wish to convert (To/From).
// After that you will have tow functions, "annotated class from target" and
// "annotated class to target".
@Converter(UserEntity)
class UserModel {
UserModel(
this.id, {
this.name,
});
final int? id;
final String? name;
factory UserModel.fromEntity(UserEntity entity) =>
_$UserModelFromUserEntity(entity);
UserEntity toEntity() => _$UserModelToUserEntity(this);
}
class UserEntity {
const UserEntity(
this.id, {
this.name,
});
final int? id;
final String? name;
}
Its so important to note that the parameters must have the same name, type, position "for the positional parameters".
Hands up, with this annotation you get out of the box the following methods:
- fromObject
- toObject
- fromJson
- toJson
@Converter(User, fromObject: 'fromEntity', toObject: 'toEntity')
@JsonSerializable()
class UserModel {
UserModel(
this.firstName,
this.lastName,
this.email,
this.phone,
this.dateOfBirth,
this.country,
this.city,
this.postalCode,
);
final String firstName;
final String lastName;
final String email;
final String phone;
final DateTime dateOfBirth;
final String country;
final String city;
final String postalCode;
}
//generated code:
static UserModel fromEntity(User user) => _$UserModelFromUser(user);
User toEntity() => _$UserModelToUser(this);
static UserModel fromJson(Map<String, dynamic> json) =>
_$UserModelFromJson(json);
Map<String, dynamic> toJson() => _$UserModelToJson(this);
// usage:
final Map<String, dynamic> json = model.toJson();
final User entity = model.toEntity();
final UserModel fromJson = UserModelConverter.fromJson(json);
final UserModel fromEntity = UserModelConverter.fromEntity(entity);
Note: static methods fromJson/fromObject must be access by
<annotated-class>Converter
extension method.
- Annotations
-
- @Target(<TargetKind>{TargetKind.classType})
Constructors
- Converter.new(Type objectType, {String? fromObject, String? toObject})
-
Accept a Type
const
Properties
- fromObject → String?
-
The custom name for the from (subject) factory method.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- objectType → Type
-
The Type of the predicate (subject).
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- toObject → String?
-
The custom name for the to (subject) method.
final
Methods
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited