what is Typedefs and what is the use of Typedefs ?
Answer
Overview
Typedef (type alias) in Dart allows you to create a named alias for a function type or any type, making complex function signatures readable and reusable.
Typedef for Function Types
dart// Without typedef -- hard to read final Map<String, void Function(String, int)> handlers = {}; // With typedef -- much cleaner typedef EventHandler = void Function(String event, int timestamp); final Map<String, EventHandler> handlers = {}; void handleClick(String event, int timestamp) { print('$event at $timestamp'); } handlers['click'] = handleClick; // Clean!
Common Uses
Callback Types
dart// Define reusable callback signatures typedef OnSuccess<T> = void Function(T data); typedef OnError = void Function(String message, Exception? error); typedef Predicate<T> = bool Function(T value); typedef JsonMapper<T> = T Function(Map<String, dynamic> json); // Use in function signatures void fetchData({ required OnSuccess<List<User>> onSuccess, required OnError onError, }) async { try { final users = await api.getUsers(); onSuccess(users); } catch (e) { onError('Fetch failed', e as Exception); } } // Use fetchData( onSuccess: (users) => setState(() => _users = users), onError: (msg, e) => showSnackBar(msg), );
Generic Typedef (Dart 2.13+)
dart// Generic type alias typedef Transformer<T, R> = R Function(T input); Transformer<String, int> strLength = (s) => s.length; Transformer<int, String> intToStr = (n) => n.toString(); print(strLength('hello')); // 5 print(intToStr(42)); // '42'
Non-function Typedef (Dart 2.13+)
dart// Type alias for any type -- not just functions typedef IntList = List<int>; typedef UserMap = Map<String, User>; typedef Coordinate = (double, double); // Record type alias IntList numbers = [1, 2, 3]; // Same as List<int> UserMap cache = {}; // Same as Map<String, User> Coordinate location = (12.97, 77.59);
In Flutter -- Practical Examples
dart// Widget builder typedef typedef WidgetBuilder = Widget Function(BuildContext context); typedef IndexedWidgetBuilder = Widget Function(BuildContext context, int index); // Builder pattern void showCustomDialog({ required WidgetBuilder builder, }) { showDialog(context: context, builder: builder); } // State management typedef StateUpdater<T> = T Function(T currentState); class Store<T> { T _state; Store(this._state); void update(StateUpdater<T> updater) => _state = updater(_state); }
Typedef vs inline Function Types
dart// Inline -- valid but verbose in complex cases void process(void Function(String, int) callback) { ... } // Typedef -- reusable and named typedef Callback = void Function(String, int); void process(Callback callback) { ... } // Cleaner
Best Use: Use typedef to name complex function signatures, make callback types reusable across files, and improve code readability. Dart 2.13+ also supports non-function type aliases.