android-studioflutterdartauto-generatejson-serializable

Shortcut for generating json_serializable (Flutter/Dart plugin) boilerplate codes in Android Studio


json_serializable plugin of Dart, does a great job of automatically generating some error prone and cumbersome parts of code, in exchange for some boilerplate: two methods, one annotation, and one reference to the generated file.

import 'package:json_annotation/json_annotation.dart';

part 'location.g.dart';

@JsonSerializable()
class Location {
  final double lat;
  final double lng;

  Location(this.lat, this.lng);

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

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

Obviously this better be done also by the machine, like the constructor for this class: I just write the final field, then press alt+enter and Android Studio places the constructor for me.

Does someone know how to make Android Studio do that for json_serializable?


Solution

  • I finally wrote this simple Live Template script. You just have to enter the file name and list of fields. See the gif below.

    import 'package:json_annotation/json_annotation.dart';
    
    part '$NAME$.g.dart'
    
    @JsonSerializable(explicitToJson: true)
    class $CAP_NAME$ {
      $END$
      
      $CAP_NAME$();
      
      factory $CAP_NAME$.fromJson(Map<String, dynamic> json) => _$$$CAP_NAME$FromJson(json);
      
      Map<String, dynamic> toJson() => _$$$CAP_NAME$ToJson(this);
    }
    

    demo

    Well, in this simple solution the mentioned boiler plate is now being generated, and this works fine for me, but it is a very naive way indeed, I didn't invest much time in learning the Live Template script. One improvement is to make it write the fields in the constructor parameter list instead of doing it manually. Another way is to use the File Template script, which I did not look into, and possibly create the file and fields in a dialog.