In Dart, typedef is used to generate an alias for function type that we can use it as type annotation for declaring variables and return types of that function type so that we can make our code better. An alias of function type can be used as type annotation in variable declaration or function return type. It stores the type information when we assigned the function type to a variable.
Syntax declaration for typedef
1 |
typedef function_name (parameters); |
Or
1 |
typedef variable_name = function_name; |
Or
1 |
variable_name(parameters); |
Let’s see an example of an implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
typedef MathOperation(int num1, int num2); Sum(int n1, int n2) { print("Sum of the two number: ${n1+n2}"); } Sub(int n1, int n2 ) { print("Subtraction of the two number: ${n1-n2}"); } void main() { MathOperation mp = Sum; print("Dart typedef Example"); mp(22,78); mp = Sub; mp(200,100); } |
In the above code, we created the alias of the MathOperation() function using the typedef keyword. We defined two more functions Sum() and Sub(), which have same signature as the typedef function.
Then, we assigned the variable mp that referred to both functions Sum() function and Sub() function. Now, we invoked the function by passing the required argument, and it printed the result to the screen as shown in the below image.
So, now as per the example explained please try this in the projects and utilize its features.