Skip to content

List data type field FromJson not getting correctly generated #41

@Vedsaga

Description

@Vedsaga

Input file

import 'package:genq/genq.dart';

part 'genq_test.genq.dart';

@Genq(json: true)
class User with _$User {
  factory User({
    @JsonKey(name: 'full_name') required List<String> name,
  }) = _User;
}

Current generated code

User $UserFromJson(Map<String, dynamic> json) {
  return User(
    name: List.of(json['full_name']).map((e) => e as String).toList(),
  );
}

As could be seen json['full_name'] data type would be dynamic, so we can't loop over it, we would need to specifically cast it be iterable. The dart analyzer will give error

The argument type 'dynamic' can't be assigned to the parameter type 'Iterable<dynamic>'. dart[argument_type_not_assignable](https://dart.dev/diagnostics/argument_type_not_assignable)

Expected generated code

User $UserFromJson(Map<String, dynamic> json) {
  return User(
    name: List.of(json['full_name'] as Iterable).map((e) => e as String).toList(),
  );
}

There were some more improvement which could be done by taking inspiration from freeze, not reporting right in this for now.

Btw, this is great initiative to improve the code gen experience for classes. Today came across the package thought to give it try, as currently when using the freeze with build running is taking ~3 min per build and can go up to ~5-8 min some times.

While macros in dart around the corner, expected to be released by early 2025 and all build runner related package expected to move to macros. Still it will good to have alternate.

Will try my best to contribute to it and improve it.

Thank you again.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions