Question #155EasyDart Basics

What is type annotation?

Answer

Overview

Type annotation in Dart is the explicit declaration of a variable's type, providing documentation and enabling compile-time type checking.


What is Type Annotation?

A type annotation is the explicit type label you write before a variable or parameter name:

dart
// Type annotation: String, int, double, bool, List<User>
String name = 'Alice';          // Type annotation: String
int age = 28;                   // Type annotation: int
double price = 9.99;            // Type annotation: double
bool isActive = true;           // Type annotation: bool
List<String> tags = ['flutter']; // Type annotation: List<String>

// Without type annotation (inferred by Dart)
var name = 'Alice';   // Dart infers String
var age = 28;         // Dart infers int

Type Annotations in Functions

dart
// Return type annotation + parameter type annotations
String greet(String firstName, String lastName) {
  return 'Hello, $firstName $lastName!';
}

// Without annotations (avoid in public APIs)
greet(firstName, lastName) {  // Bad — unclear types
  return 'Hello...';
}

// Nullable type annotation
String? findUser(int id) {
  return users.firstWhereOrNull((u) => u.id == id);
}

// Void return type annotation
void logout() {
  _user = null;
  _token = null;
}

Generic Type Annotations

dart
// Annotate list type
List<int> numbers = [1, 2, 3];
List<Map<String, dynamic>> items = [];

// Map type annotation
Map<String, int> scores = {'Alice': 95, 'Bob': 87};

// Function type annotation
bool Function(String) validator = (s) => s.isNotEmpty;

// Typedef annotation
typedef Predicate<T> = bool Function(T);

Type Annotation vs Type Inference

dart
// Explicit type annotation — always clear
List<Widget> children = [];
Map<String, UserModel> cache = {};

// Type inference — Dart figures out the type
var children = <Widget>[];                    // Same as List<Widget>
final cache = <String, UserModel>{};         // Same as Map<String, UserModel>

Benefits of Type Annotations

BenefitDescription
IDE supportAutocomplete, refactoring work correctly
DocumentationCode is self-documenting
Compile safetyErrors caught before runtime
Team clarityOthers understand your code faster

Dart Linter Rules for Type Annotations

yaml
linter:
  rules:
    - always_declare_return_types  # Require return type on all functions
    - type_annotate_public_apis    # Annotate public API types
    - avoid_types_on_closure_parameters  # Skip annotations in lambdas

Best Practice: Always annotate public API types (function signatures, class fields). Use

text
var
with type inference for local variables where the type is obvious from the right-hand side.