codec_gen 0.2.1 copy "codec_gen: ^0.2.1" to clipboard
codec_gen: ^0.2.1 copied to clipboard

Code generator for the codec package: reads @Codable / @CodecEnum annotations and generates type-safe JSON codec fields with $.path error locations, via build_runner.

example/README.md

codec_gen example #

codec_gen is a build_runner-driven code generator; it has no standalone main to run. Instead, it reads annotations in your project and generates *.g.dart files. The following shows the minimal usage.

1. Dependencies #

dependencies:
  codec: ^0.2.1

dev_dependencies:
  codec_gen: ^0.2.0
  build_runner: ^2.4.0

2. Annotate a model #

import 'package:codec/codec.dart';

part 'user.g.dart';

@Codable(includeIfNull: false)
final class User {
  const User({required this.name, required this.age, this.avatar});

  final String name;
  final int age;

  @CodecField(name: 'avatar_url')
  final String? avatar;

  static final Codec<User> codec = _$userCodec;
  factory User.fromJson(Object? json) => codec.decode(json);
  Object? toJson() => codec.encode(this);
}

3. Run the generator #

dart run build_runner build --delete-conflicting-outputs

build_runner generates user.g.dart containing _$userCodec. After that, User.fromJson(...) / user.toJson() are ready to use. On failure, the codec throws a DecodeException with a $.path error location (catch with on DecodeException).

For FormatException compatibility, either set exception_style: format in build.yaml (the generator appends .withFormatExceptions() to every top-level codec automatically), or call .withFormatExceptions() manually on the outermost codec at the call site.

For the full annotation reference (field renaming, enum mapping, DateTime modes, default values, etc.) see the codec_gen README.

1
likes
160
points
0
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Code generator for the codec package: reads @Codable / @CodecEnum annotations and generates type-safe JSON codec fields with $.path error locations, via build_runner.

Repository (GitHub)
View/report issues

Topics

#json #codec #code-generation #build-runner #serialization

License

MIT (license)

Dependencies

analyzer, build, codec, dart_style, source_gen

More

Packages that depend on codec_gen