Annotations and attributes

suggest change

Annotations (often referred to as attributes or metadata in other languages) attach structured, compile-time metadata to Dart code declarations—including classes, methods, constructors, fields, parameters, and top-level variables.

In Dart, annotations begin with an @ character and reference either a compile-time const variable or an invocation of a const constructor.


Standard Built-In Annotations

Dart provides core annotations in dart:core:

1. @override

Instructs the Dart analyzer to verify that the annotated member overrides a matching member on a superclass or implemented interface:

class BaseService {
  void execute() => print('Base execution');
}

class CustomService extends BaseService {
  @override
  void execute() {
    print('Custom execution');
  }
}

2. @Deprecated and @deprecated

Marks an API as deprecated and generates analyzer warnings for callers:

// General deprecation
@deprecated
void oldMethod() {}

// Detailed deprecation with version and replacement advice
@Deprecated('Use authenticateWithToken() instead. Will be removed in v3.0.0')
void authenticate(String user, String pass) {}

3. @pragma

Provides low-level hints to the Dart VM and Ahead-Of-Time (AOT) compiler:

// Instructs the AOT compiler to inline this function for maximum speed
@pragma('vm:prefer-inline')
int fastAdd(int a, int b) => a + b;

// Prevents tree-shaking from pruning this entry point during compilation
@pragma('vm:entry-point')
void backgroundTask() {}

Static Analysis Annotations (package:meta)

The official package:meta provides annotations that enforce architectural rules without runtime overhead:

dependencies:
  meta: ^1.19.0
import 'package:meta/meta.dart';

// 1. @immutable: Warns if any field is not final
@immutable
class Configuration {
  final String apiKey;
  final int timeoutSeconds;

  const Configuration(this.apiKey, this.timeoutSeconds);
}

class BaseController {
  // 2. @mustCallSuper: Warns if overriding subclass does not call super.dispose()
  @mustCallSuper
  void dispose() {
    print('Base controller disposed');
  }

  // 3. @protected: Only accessible from subclasses or within the same library
  @protected
  void emitState() {}

  // 4. @visibleForTesting: Intended for test suites, warns if used in normal code
  @visibleForTesting
  void resetInternalCache() {}
}

Defining Custom Annotations

Any class with a const constructor can be used as an annotation:

// Custom annotation definition
class ApiRoute {
  final String path;
  final String method;
  final bool requiresAuth;

  const ApiRoute(this.path, {this.method = 'GET', this.requiresAuth = false});
}

// Or define a constant variable directly
const auditLog = _AuditLog();

class _AuditLog {
  const _AuditLog();
}

Applying Custom Annotations

class UserController {
  @ApiRoute('/api/v1/users', method: 'GET')
  void listUsers() {}

  @ApiRoute('/api/v1/users', method: 'POST', requiresAuth: true)
  @auditLog
  void createUser() {}
}

Processing Annotations: Code Generation vs Reflection

Because Flutter and Dart web strip reflection metadata (tree-shaking) to optimize binary size and startup time, runtime reflection (dart:mirrors) is disabled in Flutter.

Instead, the Dart ecosystem processes annotations at compile time using build_runner and source_gen:

Source Code (@JsonSerializable())  ──>  build_runner (analyzer)  ──>  Generated Code (.g.dart)

Example: Compile-Time JSON Serialization

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart'; // File created by code generator

@JsonSerializable()
class UserProfile {
  final String username;
  @JsonKey(name: 'created_at')
  final DateTime createdAt;

  UserProfile({required this.username, required this.createdAt});

  factory UserProfile.fromJson(Map<String, dynamic> json) => _$UserProfileFromJson(json);
  Map<String, dynamic> toJson() => _$UserProfileToJson(this);
}

Run code generation in terminal:

dart run build_runner build --delete-conflicting-outputs

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents