Search code examples
flutterdriftbuild-runnerjson-serializable

Flutter - How to use DataClass object in a model I want to serialize?


I am using Drift (Moor) v2.0.2+1 library for my local database and json_serializable v6.3.1 library to serialize my data models. Then I use build_runner v2.2.0 library to generate boilerplate code for both.

I have a database table called Passenger Table. When running build_runner, it generates DataClass for the table, like so:

class PassengerTableData extends DataClass implements Insertable<PassengerTableData> {
  final int? id;
  final String? firstName;
  final String? lastName;
  .......
}

I want to use this DataClass class as a response object from my API calls. So, I added a data model like so:

@JsonSerializable(explicitToJson: true)
class CreatePassengerRequest {
   List<PassengerTableData?>? passengers;

   CreatePassengerRequest(this.passengers);

   factory CreatePassengerRequest.fromJson(Map<String, dynamic> json) => _$CreatePassengerRequestFromJson(json);

   Map<String, dynamic> toJson() => _$CreatePassengerRequestToJson(this);
}

When running build_runner, it also generates serializing code for this model but it is not able to generate proper code for the DataClass and only puts dynamic in its place. The result is as follows:

CreatePassengerRequest _$CreatePassengerRequestFromJson(Map<String, dynamic> json) 
                 =>CreatePassengerRequest(json['passengers'] as List<dynamic>?);  // <--- here

Since build_runner is generating code for both the libraries, could it be that when serializing code is generated for the model, the DataClass is not generated yet? Is it possible to "freeze" some files from being rebuilt when running build_runner or to change the order of files being processed by build_runner?

I tried using the build_config library but I could not make it work.


Solution

  • I was able to make it work but with a "hack".

    I was able to change the order of build by using runs_before and required_inputs in build.yaml file but it was still giving the same error. This was because the generated file of database was deleted (and regenerated) each time I ran build_runner. Even when I set enabled: false for drift_dev in the build.yaml, the file was deleted.

    So, I first ran build_runner and made sure code for all the database tables were properly generated. Then, I renamed the generated file of the database for example: database.g.dart to databaseg.dart and then ran build_runner again. This time, the generated file for the database was not deleted so json_serializable and retrofit_generator could access the DataClass objects in the file. Thus, there were no more errors!