What can Freezed+json_serializable packages do for you?
- FromJson
- toJson
- toString
- Equality override
- hashCode override
- copyWith
Setup
1. Import dependencies
flutter pub add json_annotation meta dev:build_runner dev:freezed dev:json_serializable
Pubspec.yaml should look like this
dependencies:
json_annotation:
meta:
dev_dependencies:
build_runner:
freezed:
json_serializable:
2. Exclude generated files from analysis
analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"
errors:
invalid_annotation_target: ignore
3. Watch with build runner
dart run build_runner watch
This will start watching your code and as long as the terminal session is opened it will generate the code upon our changes
4. Create class with model
import freezed annotation
specify part directives, which allows you to split a library into multiple files. but in our case it will point to the generated code.
Name must match the name of file you are generating from, and the file type .freezed.dart is for freezed and .g.dart if for json_serializable
Annotate class with @freezed, so that the build_runner would know to generate from this class
define the parameters of the class with factory ClassName and point to generated factory. This will tell Freezed, that it should build toString, Equality override, hashCode override and copyWith
define factory ClassName.fromJson and pointer to the generated toJson and FromJson. This will make toJson and FromJson
import 'package:freezed_annotation/freezed_annotation.dart';
part 'custom_place.freezed.dart';
part 'custom_place.g.dart';
@freezed
abstract class CustomPlace with _$CustomPlace {
const factory CustomPlace({
required String name,
required double latitude,
required double longitude,
}) = _CustomPlace;
factory CustomPlace.fromJson(Map<String, dynamic> json) =>
_$CustomPlaceFromJson(json);
}
Leave a Reply