free geoip
49

How to Format Dart Code Automatically

If you’re working with Dart in Android Studio or Visual Studio Code, keeping your code clean and properly formatted is…

If you’re working with Dart in Android Studio or Visual Studio Code, keeping your code clean and properly formatted is essential. Manual formatting can be time-consuming, especially as your codebase grows. Fortunately, Dart provides a built-in tool to automatically format your code, making it readable, consistent, and professional.

format Dart code automatically

In this guide, you’ll learn how to format Dart code automatically using the dart format command, and how to configure your IDE to handle formatting on save. Whether you’re working on a Flutter project or a pure Dart CLI tool, this solution is reliable and quick.

Using the Dart Formatter from Terminal

To auto-format Dart code via the terminal, follow these steps:

dart format .

This command recursively formats all Dart files in the current directory. You can also format specific files:

dart format lib/main.dart

Configure Auto Format in VS Code

  1. Open Command Palette (Ctrl+Shift+P or Cmd+Shift+P on Mac).
  2. Search: Preferences: Open Settings (JSON)
  3. Add the following setting:
"[dart]": {
  "editor.formatOnSave": true
}

Configure Auto Format in Android Studio

  1. Go to Preferences > Languages & Frameworks > Dart.
  2. Ensure that Dart is installed and SDK path is correct.
  3. Enable: Format code on save.
  4. Additionally, go to Preferences > Keymap > Main Menu > Code > Reformat Code to set custom shortcuts.

Using Format via Code (Optional Utility Class)

If you want to integrate formatting logic programmatically, use the following sample class in Dart:

formatter_helper.dart

import 'dart:io';

class DartFormatterHelper {
  /// Automatically formats Dart code using the dart format CLI.
  static Future<void> formatCode({String path = '.'}) async {
    final result = await Process.run('dart', ['format', path]);

    if (result.exitCode == 0) {
      print('Formatting complete:\n${result.stdout}');
    } else {
      print('Formatting failed:\n${result.stderr}');
    }
  }
}

main.dart

import 'formatter_helper.dart';

void main() async {
  await DartFormatterHelper.formatCode(path: 'lib/');
}

You can integrate this utility in your custom tooling or scripts for batch formatting.

Benefits of Automatic Dart Code Formatting

  • Enhances readability for teams.
  • Enforces a consistent coding style.
  • Saves time during code reviews.
  • Reduces merge conflicts caused by whitespace and indentation issues.

For deeper understanding and advanced formatting rules, you can refer to the official Dart Style Guide.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *