0
0
FlutterHow-ToBeginner · 4 min read

How to Use pubspec.yaml in Flutter: Syntax and Examples

In Flutter, pubspec.yaml is a configuration file used to manage your app’s dependencies, assets, and metadata. You edit this file to add packages, declare assets like images, and set app information before running flutter pub get to apply changes.
📐

Syntax

The pubspec.yaml file uses YAML format to declare your Flutter app’s settings. Key parts include:

  • name: Your app’s name.
  • description: A short app description.
  • version: App version number.
  • environment: Flutter SDK version constraints.
  • dependencies: Packages your app needs.
  • flutter: Flutter-specific settings like assets.
yaml
name: my_flutter_app
description: A simple Flutter app
version: 1.0.0+1
environment:
  sdk: ">=2.17.0 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
flutter:
  assets:
    - assets/images/logo.png
💻

Example

This example shows a basic pubspec.yaml file that adds the http package and includes an image asset. After editing, run flutter pub get to download packages and register assets.

yaml
name: example_app
description: Example Flutter app
version: 1.0.0+1
environment:
  sdk: ">=2.17.0 <3.0.0"
dependencies:
  flutter:
    sdk: flutter
  http: ^0.14.0
flutter:
  assets:
    - assets/images/example.png
Output
Packages downloaded and assets registered successfully.
⚠️

Common Pitfalls

Common mistakes when using pubspec.yaml include:

  • Incorrect indentation breaks YAML parsing; always use 2 spaces per level.
  • Forgetting to run flutter pub get after changes means packages or assets won’t update.
  • Wrong asset paths cause runtime errors; paths must be relative to the project root.
  • Using incompatible package versions can cause build failures.
yaml
wrong:
  dependencies:
    flutter:
      sdk: flutter
    http: ^0.14.0
flutter:
  assets:
    - assets/images/example.png

correct:
  dependencies:
    flutter:
      sdk: flutter
    http: ^0.14.0
flutter:
  assets:
    - assets/images/example.png
📊

Quick Reference

Here is a quick summary of common pubspec.yaml sections:

SectionPurposeExample
nameApp namemy_flutter_app
descriptionShort app descriptionA simple Flutter app
versionApp version1.0.0+1
environmentSDK constraintssdk: ">=2.17.0 <3.0.0"
dependenciesPackages neededhttp: ^0.14.0
flutterFlutter-specific settingsassets: - assets/images/logo.png

Key Takeaways

Always use correct YAML indentation with 2 spaces per level in pubspec.yaml.
Add dependencies and assets in pubspec.yaml, then run flutter pub get to apply changes.
Asset paths must be relative to the project root and correctly indented.
Check package versions for compatibility to avoid build errors.
pubspec.yaml controls app metadata, dependencies, and Flutter-specific settings.