On this page10 sections
Lecture 049: typedef
| Day | Extra Topics |
| Lecture | 049 of 057 |
| Estimated video length | 8 min |
| Target | Dart 3.12 |
| Level | Beginner |
Some types are long and hard to read:
int Function(int a, int b)orMap<String, dynamic>. Atypedefgives a type a short, meaningful name, so your code explains itself.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 040 (higher-order functions) and 048 (anonymous functions).
Learning Objectives
- Create a name for a function type with
typedef - Use that name for variables and parameters
- Create a short name for any other type
- Know that a
typedefis only a new name, not a new type
1. Naming a Function Type
A function that takes two ints and returns an int has the type int Function(int, int).
Give it a name:
typedef MathOperation = int Function(int a, int b);
int add(int a, int b) => a + b;
int multiply(int a, int b) => a * b;
int calculate(int x, int y, MathOperation op) => op(x, y);
void main() {
print(calculate(6, 3, add)); // 9
print(calculate(6, 3, multiply)); // 18
print(calculate(6, 3, (a, b) => a - b)); // 3
MathOperation op = multiply;
print(op(4, 5)); // 20
}calculate(int x, int y, MathOperation op) is much easier to read than
calculate(int x, int y, int Function(int, int) op).
typedef lines go at the top level of the file, outside main and outside classes.
2. Naming Other Types
A typedef works for any type, not only functions:
typedef Json = Map<String, dynamic>;
typedef Scores = List<int>;
Json user = {'name': 'Ali', 'age': 20};
print(user['name']); // Ali
Scores marks = [80, 92, 75];
print(marks.length); // 33. Just a New Name
Scores is List<int>: same type, different name. Anything that works on a List<int>
works on a Scores, and the two can be swapped freely. A typedef makes code easier to read;
it doesn't add any new rules.
Code Examples
Example 1: Form Validation Rules
Each rule takes the text the user typed and returns an error message, or null if it's fine.
typedef Validator = String? Function(String value);
String? notEmpty(String value) => value.trim().isEmpty ? 'Required' : null;
String? minLength8(String value) => value.length < 8 ? 'Must be at least 8 characters' : null;
String? hasDigit(String value) => value.contains(RegExp(r'[0-9]')) ? null : 'Must contain a number';
void check(String label, String value, List<Validator> rules) {
for (var rule in rules) {
var error = rule(value);
if (error != null) {
print('$label "$value": $error');
return;
}
}
print('$label "$value": OK');
}
void main() {
var passwordRules = <Validator>[notEmpty, minLength8, hasDigit];
check('Password', '', passwordRules);
check('Password', 'abc', passwordRules);
check('Password', 'abcdefgh', passwordRules);
check('Password', 'abcdefg1', passwordRules);
}Output
Password "": Required
Password "abc": Must be at least 8 characters
Password "abcdefgh": Must contain a number
Password "abcdefg1": OKList<Validator> reads like plain English: a list of validators. Flutter's text fields use
exactly this pattern for their validator: property.
Common Beginner Mistakes
1. Passing a function with the wrong shape
typedef MathOperation = int Function(int a, int b);
String join(String a, String b) => a + b;
MathOperation op = join;Error: A value of type 'String Function(String, String)' can't be assigned to a variable of type 'int Function(int, int)'.The parameter and return types must match.
2. Writing a typedef inside main or a class: it must be at the top level of the file.
3. Expecting a new type: typedef Age = int; doesn't stop you passing any int where an
Age is expected. For a truly separate type, write a class.
Practice Questions
- Write a
typedefnamedGreetingfor a function that takes aStringand returns aString. - With
typedef Scores = List<int>;, isScores s = [1, 2];valid? - Where in a file must a
typedefgo? - Why use
typedefat all?
Practice Answers
typedef Greeting = String Function(String name);- Yes.
Scoresis just another name forList<int>. - At the top level, outside functions and classes.
- To give long or unclear types a short, meaningful name, which makes code easier to read.
Key Takeaways
typedef Name = SomeType;gives a type a new name.- Most useful for function types:
typedef MathOperation = int Function(int a, int b); - Also handy for long types like
Map<String, dynamic>. - It's only a name; the real type is unchanged.