Search code examples
dartflutterdart-pubjson-serialization

Generating dart file with json_serializable package


According to the json_serializable package installing instructions, you should add the following dependency:

dependencies:
  json_serializable: ^2.0.3

This is my code:

import 'package:json_annotation/json_annotation.dart';

part 'person.g.dart';

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

Now running this in Flutter:

flutter packages pub run build_runner build

Or this for a Dart project:

pub run build_runner build

I get the following error:

Could not find package "build_runner". Did you forget to add a dependency?

What's wrong?


Solution

  • This is a problem with how Pub is set up to automatically generate the installation instructions. Here are the dependencies that you actually need to add:

    dependencies:
      json_annotation: ^2.0.0
    
    dev_dependencies:
      build_runner: ^1.0.0
      json_serializable: ^2.0.0
    

    This is shown in the json_serializable example.

    Now you can generate the dart file for a class like this

    import 'package:json_annotation/json_annotation.dart';
    
    part 'person.g.dart';
    
    @JsonSerializable(nullable: false)
    class Person {
      final String firstName;
      final String lastName;
      final DateTime dateOfBirth;
      Person({this.firstName, this.lastName, this.dateOfBirth});
      factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
      Map<String, dynamic> toJson() => _$PersonToJson(this);
    }
    

    by running this in a Flutter project:

    flutter packages pub run build_runner build
    

    or this in a Dart project:

    pub run build_runner build
    

    Other notes:

    • Make sure that part 'person.g.dart' matches the name of your person.dart model class file. That is, don't call it example.g.dart.