What is "typedef" in Dart/Flutter

Thu, Dec 8, 2022

Read in 2 minutes

In this post we will take a look at what Dart "typedef" is and how to use it.

In Dart, typedef is a way to define a function signature or a function type without specifying an implementation. It provides a name to a function signature, making it easier to reuse and pass around in code.

For example, let’s say we have a function that takes in two integers and returns a boolean value indicating whether they are equal or not:

bool checkEquality(int a, int b) {
  return a == b;
}

We can define a typedef for this function signature like this:

typedef EqualityChecker = bool Function(int a, int b);

Now, we can use this typedef to declare variables or parameters that hold functions with the same signature:

bool isEqual(int x, int y, EqualityChecker check) {
  return check(x, y);
}

Here, the isEqual function takes in two integers and a function that matches the signature of EqualityChecker. This function can be any function that takes in two integers and returns a boolean value.

We can use the typedef EqualityChecker to make our code more readable and reusable. For example, if we want to use a different function that checks the equality of two integers, we can simply pass in a different function that matches the EqualityChecker signature.

Dart also provides a shorthand syntax for typedefs called function types. Here’s an example:

typedef EqualityChecker = bool Function(int a, int b);

// Shorthand syntax for typedef using function types
typedef bool EqualityChecker(int a, int b);

Both of these examples define the same typedef for a function that takes in two integers and returns a boolean value.

Overall, typedefs are a powerful feature in Dart that allow for creating reusable function signatures that can be used throughout your codebase.


Shohruh AK



Category:

Flutter

Tags:



See Also

Begginer's guide to using List in Dart/Flutter
What is "async" in Dart?
What is "assert" in Dart?
What is "as" in Dart language?
What is "abstract" in Dart language?