How to run a code-generator on the top of another code-generator?

后端 未结 3 1183
遥遥无期
遥遥无期 2021-02-13 04:26

Using the source_gen stack to make a code generator, how can I make a generator that generates code that would be the input of another generator (more specifically json_se

3条回答
  •  死守一世寂寞
    2021-02-13 04:47

    It's not possible just with annotation because there maybe two packages that both have the @JsonSerializable annotation

    There are two situtations :

    • You know what other generators should run after your generator.

      • https://stackoverflow.com/a/59605830/6877472 is one of the solutions
      • you can use the other generator's code in your own generator and call their generator's.generate function. example code:
    
    class Example extends Generator {
        @override
        String generate(LibraryReader library, BuildStep buildStep) {
          return JsonSerializable().generate('''
              @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 json) => _PersonFromJson(json);
                Map toJson() => _PersonToJson(this);
              }
            ''');
         }
    
    }
    
    
    • You don't know what other generators should run after your generator.

    Unfortunately currently there is no way to tell the source_gen that your generator may produce a code that needs code generation.

    I created an issue here https://github.com/dart-lang/source_gen/issues/442 if you want to subscribe

提交回复
热议问题