google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.55k stars 395 forks source link

Generated `PerFieldToJson` class missing fields passed in `super` class constructor. #1436

Open iLoveDocs opened 1 month ago

iLoveDocs commented 1 month ago

Minimal reproducible code:

// foo.dart file
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cloud_firestore_odm/cloud_firestore_odm.dart';
import 'package:json_annotation/json_annotation.dart';

part 'foo.g.dart';

@JsonSerializable(
  createFieldMap: true,
  createPerFieldToJson: true,
)
class Foo extends Bar {
  final int age;
  Foo(this.age) : super(category: 'male');
}

abstract class Bar {
  final String category;
  Bar({required this.category});
}

@Collection<Foo>('foo')
final fooRef = FooCollectionReference();

Run dart run build_runner build -d

It will generate the foo.g.dart file. Within this file, you will find the following method:

// foo.g.dart file:
...
@override
FooQuery whereCategory({
  Object? isEqualTo = _sentinel,
  Object? isNotEqualTo = _sentinel,
  // ...
}) {
  return _$FooQuery(
    _collection,
    $referenceWithoutCursor: $referenceWithoutCursor.where(
      _$FooFieldMap['category']!,
      isEqualTo: isEqualTo != _sentinel
          ? _$FooPerFieldToJson.category(isEqualTo as String) // <-- Error
          : null,
      isNotEqualTo: isNotEqualTo != _sentinel
          ? _$FooPerFieldToJson.category(isNotEqualTo as String) // <-- Error
          : null,
      // ... 
    ),
    $queryCursor: $queryCursor,
  );
}
...

The error occurs because the generated _$FooPerFieldToJson class only has the age field and not the category field:

// foo.g.dart file:
...
abstract class _$FooPerFieldToJson {
  // ignore: unused_element
  static Object? age(int instance) => instance;
}
...

Flutter version:

Flutter 3.23.0-0.1.pre • channel beta • https://github.com/flutter/flutter.git
Framework • revision 2feea7a407 (6 weeks ago) • 2024-06-06 10:19:10 +0700
Engine • revision bb10c54666
Tools • Dart 3.5.0 (build 3.5.0-180.3.beta) • DevTools 2.36.0

Package version:

build_runner: 2.4.11
json_serializable: 6.8.0
cloud_firestore_odm_generator: 1.0.0-dev.88