0 purchases
dataclass beta
dataclass #
@DataClass annotation used for dataclass_generator
The DataClass generator generates mixin for your data class with methods:
equals (operator ==)
hashCode
toString
copyWith
Getting Started #
0. Add dependencies to pubspec.yaml #
dependencies:
dataclass: latest_version
dev_dependencies:
dataclass_generator: latest_version
copied to clipboard
1. Annotate your class with @dataClass #
The class should:
has only final fields
unnamed constructor with named parameters for all fields
@DataClass()
class Car {
final String name;
final String? manufacturer;
final double price;
Car({
required this.name,
this.manufacturer,
required this.price
});
}
copied to clipboard
2. Generate dataclass base class #
Run pub run build_runner build
Generated file
mixin _$Car {
const _$Car();
String get name;
String? get manufacturer;
double get price;
bool operator ==(other) {
if (identical(this, other)) return true;
if (other is! Car) return false;
return true &&
this.name == other.name &&
this.manufacturer == other.manufacturer &&
this.price == other.price;
}
int get hashCode {
return mapPropsToHashCode([name, manufacturer, price]);
}
String toString() {
return 'Car(name=${this.name}, manufacturer=${this.manufacturer}, price=${this.price})';
}
Car copyWith({String? name, String? manufacturer, double? price}) {
return Car(
name: name ?? this.name,
manufacturer: manufacturer ?? this.manufacturer,
price: price ?? this.price,
);
}
}
copied to clipboard
3. Extend class with generated base class #
@DataClass()
class Car with _$Car {
final String name;
final String? manufacturer;
final double price;
Car({
required this.name,
this.manufacturer,
required this.price
});
}
copied to clipboard
Collection equality
@DataClass()
class Car with _$Car {
final List<String> parts;
const Car({
@Collection(deepEquality: true) // Short-hand: @Collection()
required this.parts
});
}
copied to clipboard
FAQ #
Why you didn't use extension methods?
As the docs says that:
It is a compile-time error if an extension:
Declares a member with the same basename as a member declared by Object (==, hashCode, toString, noSuchMethod, runtimeType). This applies to both static and instance member declarations.
May I use generics?
Yes.
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.