Dart Style Guide

Official conventions for writing clean, readable Dart code

📝 What is Dart Style Guide?

The Dart Style Guide provides official conventions for formatting, naming, and organizing Dart code to ensure consistency, readability, and maintainability across all Dart projects.


// Good style example
class UserProfile {
  final String firstName;
  final String lastName;
  
  UserProfile({required this.firstName, required this.lastName});
  
  String get fullName => '$firstName $lastName';
}
                                    

Style Features:

✅ Clear class name (PascalCase)

✅ Descriptive variable names (camelCase)

✅ Proper spacing and indentation

✅ Consistent formatting

Style Categories

🏷️

Naming

Consistent naming conventions

class MyClass {}
var myVariable = 'value';
const MY_CONSTANT = 42;
📐

Formatting

Code layout and spacing

if (condition) {
  doSomething();
} else {
  doSomethingElse();
}
📁

Organization

File and code structure

import 'dart:core';
import 'package:flutter/material.dart';
import 'my_file.dart';
💬

Documentation

Comments and documentation

/// Calculates the area of a circle.
double calculateArea(double radius) {
  return pi * radius * radius;
}

🔹 Naming Conventions

Follow these naming patterns for consistency:

🔸 Classes, Enums, Typedefs (PascalCase)

// ✅ Good
class UserAccount {}
class HttpRequest {}
enum OrderStatus { pending, shipped, delivered }
typedef EventCallback = void Function();

// ❌ Bad
class userAccount {}
class httpRequest {}
enum orderStatus { pending, shipped, delivered }

🔸 Variables, Functions, Parameters (camelCase)

// ✅ Good
String firstName = 'John';
int itemCount = 10;
void calculateTotal() {}
void processUserData(String userData) {}

// ❌ Bad
String first_name = 'John';
String FirstName = 'John';
void calculate_total() {}

🔸 Constants (lowerCamelCase or SCREAMING_CAPS)

// ✅ Good - for local constants
const maxRetries = 3;
const defaultTimeout = Duration(seconds: 30);

// ✅ Good - for global constants
const MAX_RETRY_COUNT = 5;
const API_BASE_URL = 'https://api.example.com';

// ❌ Bad
const Max_Retries = 3;
const DEFAULTTIMEOUT = Duration(seconds: 30);

🔹 Code Formatting

Consistent formatting makes code easier to read:

🔸 Indentation and Spacing

// ✅ Good - 2 spaces indentation
class Calculator {
  double add(double a, double b) {
    return a + b;
  }
  
  double multiply(double a, double b) {
    if (a == 0 || b == 0) {
      return 0;
    }
    return a * b;
  }
}

// ❌ Bad - inconsistent spacing
class Calculator{
double add(double a,double b){
return a+b;
}
}

🔸 Line Length and Breaking

// ✅ Good - break long lines
String createMessage(String name, String action, DateTime timestamp) {
  return 'User $name performed $action at ${timestamp.toIso8601String()}';
}

// ✅ Good - method chaining
final result = users
    .where((user) => user.isActive)
    .map((user) => user.name)
    .toList();

// ❌ Bad - too long
String createMessage(String name, String action, DateTime timestamp) {
  return 'User $name performed $action at ${timestamp.toIso8601String()} and this line is way too long to read comfortably';
}

🔹 Import Organization

Organize imports in a specific order:

// ✅ Good - proper import order
// 1. Dart core libraries
import 'dart:async';
import 'dart:io';

// 2. External packages
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

// 3. Internal packages
import 'package:my_app/models/user.dart';
import 'package:my_app/services/api_service.dart';

// 4. Relative imports
import '../utils/helpers.dart';
import 'widgets/custom_button.dart';

class MyWidget extends StatelessWidget {
  // Widget implementation
}

🔹 Documentation Style

Write clear documentation comments:

🔸 Class Documentation

/// A service for managing user authentication.
/// 
/// This class handles login, logout, and token management
/// for the application's authentication system.
/// 
/// Example usage:
/// ```dart
/// final auth = AuthService();
/// await auth.login('[email protected]', 'password');
/// ```
class AuthService {
  /// Logs in a user with email and password.
  /// 
  /// Returns `true` if login is successful, `false` otherwise.
  /// Throws [AuthException] if credentials are invalid.
  Future login(String email, String password) async {
    // Implementation
  }
}

🔸 Function Documentation

/// Calculates the distance between two points.
/// 
/// Uses the Pythagorean theorem to calculate the Euclidean
/// distance between [point1] and [point2].
/// 
/// Returns the distance as a [double].
double calculateDistance(Point point1, Point point2) {
  final dx = point1.x - point2.x;
  final dy = point1.y - point2.y;
  return sqrt(dx * dx + dy * dy);
}

🔹 Best Practices

Additional style recommendations:

🔸 Use Type Annotations

// ✅ Good - explicit types
List names = ['Alice', 'Bob', 'Charlie'];
Map scores = {'Alice': 95, 'Bob': 87};
Future fetchUser(int id) async { /* ... */ }

// ❌ Avoid - unclear types
var names = ['Alice', 'Bob', 'Charlie'];
var scores = {'Alice': 95, 'Bob': 87};

🔸 Prefer Expression Bodies

// ✅ Good - concise expression body
String get fullName => '$firstName $lastName';
bool get isAdult => age >= 18;
double calculateArea(double radius) => pi * radius * radius;

// ❌ Verbose - unnecessary block body
String get fullName {
  return '$firstName $lastName';
}

🔸 Use Trailing Commas

// ✅ Good - trailing commas for better formatting
final user = User(
  name: 'John Doe',
  email: '[email protected]',
  age: 30,
);

final colors = [
  Colors.red,
  Colors.green,
  Colors.blue,
];

🔹 Dart Formatter

Use dart format to automatically format your code:

Automatic Formatting:

  • Command: dart format . - Format all files
  • IDE Integration: Most editors auto-format on save
  • CI/CD: Include formatting checks in your pipeline
  • Consistency: Eliminates style debates in teams
// Before formatting
class MyClass{
String name;int age;
MyClass(this.name,this.age);
void display(){print('Name: $name, Age: $age');}}

// After dart format
class MyClass {
  String name;
  int age;
  
  MyClass(this.name, this.age);
  
  void display() {
    print('Name: $name, Age: $age');
  }
}

🧠 Test Your Knowledge

What naming convention should be used for Dart class names?