Generate simple data classes for Dart.
A data class is an immutable class meant to hold data, similar to Kotlin's data class.
Specify the data class using the @data annotation:
@dataclass$Point {
double x;
double y;
}Enjoy your generated named constructor, ==/hashCode, toString, copyWith, and serialization:
// GENERATED CODE - DO NOT MODIFY BY HAND@immutableclassPoint {
finaldouble x;
finaldouble y;
constPoint({
@requiredthis.x,
@requiredthis.y,
});
@overridebooloperator==(Object other) =>identical(this, other) ||
other isPoint&&
runtimeType == other.runtimeType &&
x == other.x &&
y == other.y;
@overrideintget hashCode => x.hashCode ^ y.hashCode;
@overrideStringtoString() {
return'Point{x: '+ x.toString() +', y: '+ y.toString() +'}';
}
PointcopyWith({
double x,
double y,
}) {
returnPoint(
x: x ??this.x,
y: y ??this.y,
);
}
Point.fromMap(Map<String, dynamic> m)
: x = m['x'],
y = m['y'];
Map<String, dynamic> toMap() => {'x': x, 'y': y};
factoryPoint.fromJson(String json) =>Point.fromMap(jsonDecode(json));
StringtoJson() =>jsonEncode(toMap());
}Add the following to your pubspec.yaml:
dependencies:
auto_data: ^0.0.3dev_dependencies:
build_runner: ^1.0.0auto_data_generator: ^0.0.3Create your point.dart file with correct imports:
import'package:meta/meta.dart';
import'package:collection/collection.dart';
import'package:auto_data/auto_data.dart';
import'dart:convert';
part'point.g.dart';
@dataclass$Point {
double x;
double y;
}Lastly, generate using build_runner:
pub run build_runner build
or
pub run build_runner watch
Use your generated Point class:
import'point.dart';
final p1 =Point(x:0, y:1);
final p2 =Point(x:0, y:2);
assert(p1 != p2);
final p3 = p1.copyWith(y:2);
assert(p2 == p3);
print(p3.toString());import'package:collection/collection.dart';
import'package:meta/meta.dart';
import'package:auto_data/auto_data.dart';
import'dart:convert';
import'foo.dart';
part'person.g.dart';
/// All comments are copied to generated code@dataclass$Person {
/// This field gets a default valueString name ='Paul';
/// This field is not required@nullabledouble weight;
/// Age of the personint age;
/// Depend on another generated class$Foo foo;
/// Deep comparison of listsList<$Person> friends;
/// Custom constructors are copied over$Person.genius()
: name ='Albert',
age =140;
}- Optional constructor types (named, private, const, etc)
- Custom constructors should be copied over (Issue #1)
- Default values by assigning during declaration:
String name = 'Paul'; - Add @nullable annotation for fields that are not required
- Deep immutability for Map
- Deep immutability for List
- Serialization toMap/fromMap
- Serialization toJson/fromJson
Ex) Clearing a user's avatar image:
profile = profile.copyWith(imageUrl:null); // This won't have an effect since copyWith ignores null input parameters.