Typedef in dart with examples

Typedef in dart :

typedef is a function-type alias. Functions are objects in dart-like any other type. typedef are alias for functions. typedef keyword is used to define a typedef.

How to create and use a typedef :

We can define a function signature using typedef. That signature can be used by different functions. Its syntax is as like below :

typedef name(params)

We can assign this typedef to a variable and using that variable, we can invoke the functions of that typedef. We can change that variable to point to any different method of the same typedef.

Example of typedef :

Let me show you one example of how typedef works. We will create one typedef that take one String parameter and return different types of string messages :

typedef Greet = String Function(String name);

You can also define it as :

typedef Greet(String name);

Now, we can create different functions that follows this typedef :

String SayHello(String name) {
  return "Hello $name";
}

String SayGoodBye(String name) {
  return "Good Bye $name !";
}

String SayHappyBirthday(String name) {
  return "Happy Birthday $name !";
}

Finally, we can create one variable of type Greet and assign it different types :

Greet greet;

greet = SayHello;
print(greet("Alex"));

greet = SayGoodBye;
print(greet("Bob"));

greet = SayHappyBirthday;
print(greet("Alex"));

Complete program :

typedef Greet(String name);

String SayHello(String name) {
  return "Hello $name";
}

String SayGoodBye(String name) {
  return "Good Bye $name !";
}

String SayHappyBirthday(String name) {
  return "Happy Birthday $name !";
}

main(List<string> args) {
  Greet greet;

  greet = SayHello;
  print(greet("Alex"));

  greet = SayGoodBye;
  print(greet("Bob"));

  greet = SayHappyBirthday;
  print(greet("Alex"));
}

It will print the below output :

Hello Alex
Good Bye Bob !
Happy Birthday Alex !

Similar tutorials :