N Kaushik

Fix - Flutter error Expected a key while parsing a block mapping

January 16, 2022

Flutter error: Expected a key while parsing a block mapping:

Flutter uses pub as the packaging system. You have to work with the pubspec.yaml file. This file is used for defining third-party library, assets folders etc. Once you create a sample Flutter project, a default pubspec.yaml file is created with some default configs and a few commented config lines.

This is a common error in Flutter. Mostly if you are starting Flutter development, there is a good chance that you will see this.

The reason and solution is simple. You need to check the indentation. Let me show you how the error looks like and how to fix this:

The error:

This error occurs while you try to run your Flutter app. It throws the error and it looks something like below:

Flutter error expected a key while parsing a block mapping

This error also shows the line where you need to fix the spacing. For the above example, it is assets.

How to fix this error:

The error is because the line is indented too far. You need to fix this inside the pubspec.yaml file. The indentation or the left space for that file should be same.

If the error is at assets, make sure that the start of uses-material-design and assets are vertically aligned. The left spacing for both should be same.

uses-material-design: true

assets:
    - images/user.png

If you are not sure what the spacing should be, you can search for other Flutter projects in Github to find it out.

Even if there is a small difference of spacing, it will not work. For example,

flutter:
  uses-material-design: true
   assets:
    - images/user.jpg

It will not work because the start of uses-material-design and assets are not aligning vertically.

You need to change it as like this:

flutter:
  uses-material-design: true
  assets:
    - images/user.jpg

If you are uncommeting the assets line in the default pubspec.yaml, make sure that the alignment is correct. Alignment is important in yaml files and this is the reason of many errors you will find in Flutter.


Subscribe to my Newsletter