4

The json_serializable package discussed here generates class.g.dart files, but I'd like to keep my generated files in a separate path.

I've attempted creating a directory generated_json/ and specifying part 'generated_json/class.g.dart'; in my class.dart file. This doesn't seem to have any effect, the files are still generated in the same directory as class.dart.

Is there a way to specify a custom path?

Elli White
  • 1,440
  • 1
  • 12
  • 21

2 Answers2

4

Turns out this is not possible currently with json_serializable. Discussion can be found here on the json_serializable wiki.

Elli White
  • 1,440
  • 1
  • 12
  • 21
2

It is possible using build.yaml, refer to this answer

Step 1:

  • create build.yaml, place in root project folder

    targets:
    $default:
      builders:
        source_gen:combining_builder:
          options:
            build_extensions:
              '^lib/classes/{{}}.dart': 'lib/generated/{{}}.g.dart'
    

Step 2:

  • inside lib/classes , create your model annotated with @JsonSeriazable(), i will give a bit example
import 'package:json_annotation/json_annotation.dart';
part '../generated/product.g.dart'; // generated file will stored inside lib/generated folder

@JsonSerializable()
class Product {
  final int? id;
  final String? name;
  final int? price;

  Product({
    this.id,
    this.name,
    this.price,
  });

  factory Product.fromJson(Map<String, dynamic> json) =>
      _$ProductFromJson(json);

  Map<String, dynamic> toJson() => _$ProductToJson(this);
}

Step 3:

  • run build runner
flutter pub run build_runner watch --delete-conflicting-outputs
wahyudotdev
  • 81
  • 2
  • 4