Search code examples
jsonflutter

Flutter JSON Serialization - Not generating *.g.dart files


I am new to flutter and the objective is to serialise complex JSON objects which contain other smaller objects.

Using the json_serializable: ^2.0.0 and the pubspec.yaml file looks something like this.

dependencies:
  intl: ^0.15.7
  json_annotation: ^2.0.0
  built_value: ^6.7.1
  flutter:
    sdk: flutter

dev_dependencies:
  build_runner: ^1.0.0
  json_serializable: ^2.0.0
  built_value_generator: ^6.7.1
  flutter_test:
    sdk: flutter

The user.dart look like this

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable(nullable: false)
class User {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  User({this.firstName, this.lastName, this.dateOfBirth});
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

I have tried flutter pub run build_runner build yet the file user.g.dart doesn't get created and I am facing issue with that.

I also have added the build.yaml file with following code

targets:
  $default:
    builders:
      built_value_generator|built_value:
        generate_for:
          - model/*.dart
      json_serializable|json_serializable:
        generate_for:
          - model/*.dart

Can anyone let me know what I am missing here. Thanks


Solution

  • The constructor's argument shouldn't be optional

    User({this.firstName, this.lastName, this.dateOfBirth});
    

    They should be obligatory:

    User(this.firstName, this.lastName, this.dateOfBirth);
    

    And the part

    'user.g.dart';
    

    should be matching the Uppercase User class:

    part 'User.g.dart';