What is Annotations in flutter ? example it is resemble by “@” symbol
#flutter
Answer
Overview
Annotations in Flutter/Dart are metadata markers prefixed with
text
@Built-in Dart Annotations
dart// @override -- tells compiler this overrides a parent method class Dog extends Animal { void makeSound() => print('Woof'); } // @deprecated -- marks API as outdated void oldFunction() { ... } // Use @Deprecated for message ('Use newFunction() instead -- removed in 3.0') void oldFunction2() { ... } // @protected -- should only be called by subclasses import 'package:meta/meta.dart'; class BaseWidget extends StatelessWidget { Widget buildContent(BuildContext context) => Container(); } // @immutable -- all fields must be final class Config { final String apiUrl; final int timeout; const Config({required this.apiUrl, required this.timeout}); } // @visibleForTesting -- public but not part of public API void internalSetup() { ... }
Code Generation Annotations (Most Common)
dart// json_serializable -- generate fromJson/toJson import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; // Generated file () class User { final String name; final int age; (name: 'email_address') // Map different JSON key final String email; (defaultValue: 'guest') // Default if missing final String role; const User({required this.name, required this.age, required this.email, required this.role}); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); Map<String, dynamic> toJson() => _$UserToJson(this); } // Run: flutter pub run build_runner build
dart// freezed -- generate immutable classes + pattern matching import 'package:freezed_annotation/freezed_annotation.dart'; part 'result.freezed.dart'; class ApiResult<T> with _$ApiResult<T> { const factory ApiResult.success(T data) = Success; const factory ApiResult.failure(String message) = Failure; const factory ApiResult.loading() = Loading; } // Usage final result = ApiResult.success(user); result.when( success: (data) => print(data), failure: (msg) => print(msg), loading: () => print('Loading'), );
Riverpod Annotations
dartimport 'package:riverpod_annotation/riverpod_annotation.dart'; part 'user_provider.g.dart'; Future<User> fetchUser(FetchUserRef ref, {required int id}) async { final api = ref.watch(apiServiceProvider); return api.getUser(id); } // Equivalent to manually writing FutureProvider.family
Annotation Categories
| Category | Examples |
|---|---|
| Built-in Dart | text text text |
| Meta package | text text text |
| Code generation | text text text |
| Testing | text text |
Summary: Annotations are
markers. Built-in ones guide the analyzer. Code generation annotations (text@metadata,text@JsonSerializable) drivetext@freezedto generate boilerplate code automatically.textbuild_runner