99

I have read the description, and I understand that it is a function-type alias.

But how do I use it? Why declaring fields with a function-type? When do I use it? What problem does it solve?

I think I need one or two real code examples.

MendelG
  • 14,885
  • 4
  • 25
  • 52
Gero
  • 12,993
  • 25
  • 65
  • 106
  • Note that this question is strictly related to **function** typedefs. In Dart 2.13, a new feature was added that supports *generalized* type aliases for all types. I created a new questions for this: https://stackoverflow.com/q/66847006/6509751. All answers here (and the question) only discuss the legacy format, which is why that was necessary. – creativecreatorormaybenot Mar 28 '21 at 23:14

7 Answers7

122

A common usage pattern of typedef in Dart is defining a callback interface. For example:

typedef void LoggerOutputFunction(String msg);

class Logger {
  LoggerOutputFunction out;
  Logger() {
    out = print;
  }
  void log(String msg) {
    out(msg);
  }
}

void timestampLoggerOutputFunction(String msg) {
  String timeStamp = new Date.now().toString();
  print('${timeStamp}: $msg');
}

void main() {
  Logger l = new Logger();
  l.log('Hello World');
  l.out = timestampLoggerOutputFunction;
  l.log('Hello World');
}

Running the above sample yields the following output:

Hello World
2012-09-22 10:19:15.139: Hello World

The typedef line says that LoggerOutputFunction takes a String parameter and returns void.

timestampLoggerOutputFunction matches that definition and thus can be assigned to the out field.

Let me know if you need another example.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Cutch
  • 3,511
  • 1
  • 18
  • 12
  • looks good. You have any good example where return type string is? – Gero Sep 23 '12 at 13:46
  • Shouldnt it be `new DateTime.now().toString()` ? – lordvcs Feb 24 '18 at 07:54
  • 26
    Note; this answer uses the legacy `typedef` notation. The preferred one is `typedef LoggerOutputFunction = void Function(String msg);` (from https://www.dartlang.org/guides/language/effective-dart/design#dont-use-the-legacy-typedef-syntax) – harm Aug 23 '18 at 07:52
  • 1
    please give me another example @Cutch – devmrh Sep 07 '18 at 06:02
  • Is typedef used to give another name to just callback interface? Or it works with any types. I tried something like `typedef currency double`. Error : ' Typedefs must have an explicit list of parameters.' – BangOperator Jul 01 '19 at 17:47
  • 3
    Don't forget that in Dart everything is an Object, even functions (methods). That means you can assign a function to a variable. This may be surprising to Java users. – Kirill Karmazin Aug 05 '19 at 09:59
  • 1
    @BangOperator currently typedefs supports only function types, there is an open issue for supporting non-function types, like your example using double. https://github.com/dart-lang/language/issues/65 – Julio Henrique Bitencourt Sep 04 '19 at 20:46
  • 1
    Now, Dart (starting with Dart 2.13) also supports generalized typedefs for non-function types. See the following answer for more information: https://stackoverflow.com/a/66847007/6509751 – creativecreatorormaybenot Apr 06 '21 at 20:12
33

Dart 1.24 introduces a new typedef syntax to also support generic functions. The previous syntax is still supported.

typedef F = List<T> Function<T>(T);

For more details see https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md

Function types can also be specified inline

void foo<T, S>(T Function(int, S) aFunction) {...}

See also https://www.dartlang.org/guides/language/language-tour#typedefs

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
28
typedef LoggerOutputFunction = void Function(String msg);

this looks much more clear than previous version

Joey
  • 1,436
  • 2
  • 19
  • 33
11

Just slightly modified answer, according to the latest typedef syntax, The example could be updated to:

typedef LoggerOutputFunction = void Function(String msg);

class Logger {
  LoggerOutputFunction out;
  Logger() {
    out = print;
  }
  void log(String msg) {
    out(msg);
  }
}

void timestampLoggerOutputFunction(String msg) {
  String timeStamp = new Date.now().toString();
  print('${timeStamp}: $msg');
}

void main() {
  Logger l = new Logger();
  l.log('Hello World');
  l.out = timestampLoggerOutputFunction;
  l.log('Hello World');
}
Ted Zhang
  • 341
  • 2
  • 6
  • 1
    May you say why you assigned `print` to `out`? what is the `print`? – Mo Meshkani Sep 12 '19 at 14:00
  • `print` is Dart's print function, so in the default constructor will assign print method to out which means if we didn't supply the func, it will use the default print one which comes from Dart. https://api.dart.dev/stable/2.5.0/dart-core/print.html – Ted Zhang Sep 18 '19 at 02:11
7

Typedef in Dart is used to create a user-defined function (alias) for other application functions,

Syntax: typedef function_name (parameters);

With the help of a typedef, we can also assign a variable to a function.

Syntax:typedef variable_name = function_name;

After assigning the variable, if we have to invoke it then we go as:

Syntax: variable_name(parameters);

Example:

// Defining alias name
typedef MainFunction(int a, int b);

functionOne(int a, int b) {
  print("This is FunctionOne");
  print("$a and $b are lucky numbers !!");
}

functionTwo(int a, int b) {
  print("This is FunctionTwo");
  print("$a + $b is equal to ${a + b}.");
}

// Main Function
void main() {
  // use alias
  MainFunction number = functionOne;

  number(1, 2);

  number = functionTwo;
 // Calling number
  number(3, 4);
}

Output:

This is FunctionOne
1 and 2 are lucky numbers !!
This is FunctionTwo
3 + 4 is equal to 7
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
3

Since dart version 2.13 you can use typedef not only with functions but with every object you want.

Eg this code is now perfectly valid:

typedef IntList = List<int>;
IntList il = [1, 2, 3];

For more details see updated info: https://dart.dev/guides/language/language-tour#typedefs

Ilia Kurtov
  • 999
  • 1
  • 12
  • 18
0

https://www.tutorialspoint.com/dart_programming/dart_programming_typedef.htm

 typedef ManyOperation(int firstNo , int secondNo);   //function signature 
    Add(int firstNo,int second){ 
       print("Add result is ${firstNo+second}"); 
    }  
    Subtract(int firstNo,int second){
       print("Subtract result is ${firstNo-second}"); 
    }  
    Divide(int firstNo,int second){ 
       print("Divide result is ${firstNo/second}"); 
    }  
    Calculator(int a,int b ,ManyOperation oper){ 
       print("Inside calculator"); 
       oper(a,b); 
    }  
    main(){ 
       Calculator(5,5,Add); 
       Calculator(5,5,Subtract); 
       Calculator(5,5,Divide); 
    } 
Mohamed Ayad
  • 606
  • 4
  • 12