Add Your Heading Text Here

In dart, Typedef is a keyword used to declare alias or reference to the function in the program. With the help of this alias or reference we can call different functions having same signature(i.e., having same number of parameters with same data types). For typedef, return type does not considered as part of the function signature.

In short, typedef is used to call(refer) the different functions having the same signature assigned to typedef for smoother function manipulation.

Syntax :

// Here, parameterList stands for different types of parameters required in function.
typedef variableName(parameterList);

For ex :

// here,  SportLegends is the typedef variable which can be assigned to the different functions having same signature as declared with typedef.
typedef SportLegends(String Player1,String Player2);

// Tennis function have same signature(i.e., both String type parameters) as typedef SportLegends().
Tennis(String Player1, String Player2){
  print("$Player1 and $Player2 are two great players of tennis.");
}

// Cricket function have same signature(i.e., both String type parameters) as typedef SportLegends().
Cricket(String Player1,String Player2){
  print("$Player1 and $Player2 are two great players of Cricket.");
}

// Cricket function have same signature(i.e., both String type parameters) as typedef SportLegends().
Football(String Player1,String Player2){
  print("$Player1 and $Player2 are two great players of Football.");
}

void main(){
  SportLegends legends;
  // assigning typedef to reference the Tennis function having the same signature as typedef  SportLegends.
  legends=Tennis;
  legends("Roger Federer","Rafael Nadal");
  legends=Cricket;
  legends("Sachin Tendulkar","AB De Villiars");
  legends=Football;
  legends("Cristiano Ronaldo","Lionel Messi");
}

Output :

Roger Federer and Rafael Nadal are two great players of tennis.
Sachin Tendulkar and AB De Villiars are two great players of Cricket.
Cristiano Ronaldo and Lionel Messi are two great players of Football.

Hence, typedef becomes really useful to point-out different functions having same signature with single variable to reduce boiler-plate coding.

It can be useful to learn typedef as it makes your work very handy to map different functions with single variable as per your requirements.

Feel free to ask your questions in the comment section. Keep reading and commenting your suggestions to make toastguyz a better site to learn different programming languages.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Show Buttons
Hide Buttons