With Flutter, you can easily automate tasks like formatting, linting and testing your code with the help of pre-commit hooks.

What is Flutter

Flutter is an open-source software development kit created by Google that enables developers to create apps for Android, iOS, Windows, Mac, Linux, and the web from a single codebase. It uses a programming language called Dart and a reactive framework called Flutter that allows for fast development of apps with a modern user interface. Apps made with Flutter have been used by some of the world’s largest companies, such as Alibaba, Google, and eBay.

What are pre-commit hooks

Pre-commit hooks are scripts that run before a commit is made in a version control system. They are used to perform a variety of tasks such as checking for syntax errors, formatting code, or running unit tests. They allow developers to ensure that only code that meets certain standards is committed. This helps to maintain code quality and reduce errors.

Let’s use pre-commit hooks with flutter

Prequisites

  • install pre-commit
  • initialise pre-commit hooks for your repository using pre-commit install inside your repo directory
  • To setup your pre-commit hooks you need to create a .pre-commit-config.yaml file

Example pre-commit config

Our example .pre-commit-config.yaml will format, analyze and test your flutter code

repos:
-   repo: https://github.com/Cretezy/flutter-format-pre-commit
    rev: "master"
    hooks:
    -   id: flutter-format
-   repo: https://github.com/dluksza/flutter-analyze-pre-commit
    rev: "master"
    hooks:
    -   id: flutter-analyze
-   repo: https://github.com/Virtomize/flutter-test-pre-commit
    rev: "main"
    hooks:
    -   id: flutter-test

You can find even more hooks on pre-commit.com supported hooks

Hints

  • Use pre-commit autoupdate to update the rev to a specific commit instead of using main or master branches, many commit hooks also use tagged versions.
  • We run formatting and import sorting on file save when writing our flutter code and only run flutter analyze and flutter test as pre-commit hooks.
  • flutter analyze is a great tool which comes with a analysis_options.yaml once you created your flutter project

Flutter analyze

To get the maximum out of your pre-commit hooks you should customize your analysis_options.yaml file. A great example is the default analysis_options.yaml from the flutter project itself .

We use a slight variation of this one and removed a few linters that give us some issues:

That’s it we hope that helps you to improve your flutter code.