Skip to content

generated code fails static analysis strong type checking #247

Closed
@diablodale

Description

@diablodale

The code generated does not have types on several parameters. It also implicitly casts to a more specific type. This is loosely typed and fails static analysis w/ strong checking.

The generated code functions. Rather, these errors appear in IDEs and other tools that digest code analysis. So the fix is to provide a way to understand or rid the errors.

Setup

  • json_serializable 0.5.8
  • flutter 0.5.1
  • analysis_options.yaml with the following:
analyzer:
  strong-mode:
    implicit-casts: false
    implicit-dynamic: false

Repo steps

  1. Write a flutter app
  2. Create object Item which has some simple fields like a String and int.
  3. Create object MyGroup which has a field List<Item> myItems; and Set<Item> myItemSet;
  4. Annotate these objects and use common json_serializable procedure for them.
  5. flutter packages pub run build_runner build
  6. View the code in your IDE.

Result

Errors in your IDE for that generated code. You can see in the dart files and the missing param types.
In the below generated code, the e has no type declared. Then, the Iterable created from the Json is being assigned to a Set.

MyGroup _$MyGroupFromJson(Map<String, dynamic> json) {
  return new MyGroup(
      myItems: (json['myItems'] as List)
          ?.map((e) => e == null
              ? null
              : new Item.fromJson(e as Map<String, dynamic>))
          ?.toList(),
      myItemSet: (json['myItemSet'] as List)?.map((e) =>
          e == null ? null : new Item.fromJson(e as Map<String, dynamic>)),
  );
}

Possible Quick Fixes

  • Setup analysis_options.yaml to ignore the generated files with a glob that matches only the generated files with loose types.

or

  • Put dynamic before the two scenarios having the e parameter.
  • Put the type after the .map, for example ?.map<Item>((
  • Put new Set<Item>.from(...) around the whole Iterable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions