Search code examples
flutterdartbuildcode-generationbuild-runner

How to debug flutter build_runner build in VS Code?


Problem statement:

I am building a code generator with the build_runner package.

I run flutter pub run build_runner build to execute my code generators.

Question:

How can I debug flutter pub run build_runner build with breakpoints?

Similar questions:

How run flutter 'packages pub run build_runner build' with debug mode in intellij idea?


Solution

  • Since I found How run flutter 'packages pub run build_runner build' with debug mode in intellij idea? I was wondering how this works in VS Code. Furthermore, I didn't liked the solution with copying the build file. This is how i got it working.

    Generating the script:

    The first thing to do is executing flutter pub run build_runner build so the files in the .dart_tool folder are generated. My app is called meal_app.

    Folder structure

    The code generator script is located in .dart_tool/build/entrypoint/build.dart.

    Running the script:

    The script can be run with dart .dart_tool/build/entrypoint/build.dart build but that is just executing, not debugging the script. For convenient debugging the VS Code launch.json needs to be adjusted.

    Create a launch.json

    The launch.json file configures the launch configurations in VS Code. To create a launch.json select the debug symbol on the right and create the launch.json file.

    Create a launch.json

    Create a launch configuration for build_runner

    {
        "version": "0.2.0",
        "configurations": [
            {
                // Config 1
            },
            {
                // Config 2
            },
            {
                "name": "Debug Widgetbook Generator",
                "cwd": "example/meal_app",
                "request": "launch",
                "program": ".dart_tool/build/entrypoint/build.dart",
                "type": "dart",
                "args": ["build"]
            }        
        ]
    }
    

    cwd: [Probably not required] The app for which build_runner is generating files is called meal_app. The meal_app is located in a subfolder called example. Thats why the cwd property is set in the configuration. If your app is not located in a subfolder, you can omit this option.

    args: Set to "build". This is similar to the command flutter pub run build_runner build where build is the argument of build_runner.

    program: Since the code generator file is located in the structure mentioned above, the configuration needs to know which file to execute.

    name: This is the name of the configuration.

    Don't forget to switch to the correct configuration