What is a Typedef?
When you're coding in Dart, you often have functions or complex types that you use repeatedly. They can sometimes look long and make your code harder to read.
Making Functions Clearer
Imagine you need a function that takes an integer and returns nothing. You can use a typedef to give this function signature a simple name, like OnClickEvent
.
typedef OnClickEvent = void Function(int index);
Now, whenever you need a function that matches this pattern, you can just say it's an OnClickEvent
. This makes your code easier to understand and ensures you use the right function type.
Using the Restricted Function
If you have a widget that needs a function like this, you can define it using your new typedef name:
class MyButton extends StatelessWidget {
final OnClickEvent onClick;
const MyButton({
Key? key,
required this.onClick,
}) : super(key: key);
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (context, index) => InkWell(
onTap: () => onClick(index),
),
);
}
}
This clearly shows that the onClick
property expects a function that matches the OnClickEvent
pattern.
Aliasing Other Types
Before Dart version 2.13, typedefs were mainly for function types. But now, you can use them to give simple names to any complex type.
For example, if you have a nested map type like Map<String, Map<String, num>>
, you can alias it:
typedef ComplexMap = Map<String, Map<String, num>>;
Then you can use this alias like a regular type:
final ComplexMap myMap = {}; // Use your simple name!
Typedefs with Generics
Typedefs can also work with generics, making them even more flexible.
typedef ComplexMap<T> = Map<String, Map<String, T>>;
This allows you to create a complex map where the innermost value type can be specified when you use the alias.
Using typedefs helps you write cleaner, more readable, and type-safe code.