Should I Add Generated Dart Files to Git?

Monday, Jun 17, 2019| Tags: flutter

Packages like json_serializable or build_value facilitate the life of Flutter developers by generating code that is tedious to write, like JSON parsers or object builders.

The way we generate code in Flutter is currently changing as we speak.

Traditionally, what we would do is:

  1. Add the desired package to our pubspec.yaml, like the build_value
dependencies:  
  built\_value: ^6.6.0

2. Add the build_runner package to our dev_dependencies:

dev\_dependencies:  
  build\_runner: ^1.5.2  
  built\_value\_generator: ^6.6.0

3. Write our code, for example:

abstract class Message implements Built<Message, MessageBuilder> {  
  String get id;  
  // etc...  
}

4. Generate the files with this command:

flutter packages pub run build_runner build

This generates a file with the ending .g.dart.

In the recent versions of Flutter (e.g. master channel) you can run the 4th step with flutter generate or, as I understand, it will run automatically when you run flutter build and flutter run!

For that, you also need to change your pubspec.yaml and use the new builders section:

builders:  
  built\_value\_generator: ^6.6.0

Now the question is: **Should I add the ****.g.dart** files to git?

The community is divided on that, so I will expose some pros and cons and let you decide:

Pros of adding generated files to source control:

  • You don’t need to generate this sources each time you pull changes from git.
  • You don’t need to generate this sources on your CI before compiling/testing/analyze.
  • You don’t need to tell your colleagues to re-generate the files when you change something.
  • build_runner might be too slow, so you avoid running it when not required.

Cons of adding generated files to source control:

  • There is no warranty that all files are going to be in sync.
  • It is discouraged by the [build_runner](https://pub.dev/packages/build_runner) documentation.
  • More merge/rebase conflicts to deal with.

Seems that the pros are clear, you avoid having to generate them each time you pull code changes “just in case” there was a change that affected them.

However, with the new flutter generate that would not be required anymore.

On the other hand, the build speed can also become a problem for you and your team, and you may want to avoid running the generate command all the time.

I think that both options have valid points.

If you decide to not to add them, you can do so by adding this to your .gitignore:

# Generated Dart files  
**/*.g.dart

Later, if it becomes a problem for your team, you can add them. It is easier to add them later on that to remove them from source control.

Want to learn more Android and Flutter? Check my courses here.

INTERESTED IN WORKING TOGETHER?

Contact with me