Should I Add Generated Dart Files to Git?

Dealing with generated files in Flutter

Miguel Beltran
Jun 17 · 2 min read

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
built_value: ^6.6.0

2. Add the build_runner package to our 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:

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:

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

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.

Flutter Community

Articles and Stories from the Flutter Community

Miguel Beltran

Written by

Freelance Mobile Developer for Android and Flutter.

Flutter Community

Articles and Stories from the Flutter Community