Typedef and Callbacks

typedef is what is used to create callback types like VoidCallback, which is a void callback type for functions that don’t require arguments. A callback is a kind of closure that is provided as an argument to a function to be called when some conditions are met. A closure is a function that is defined a lot like a variable. The VoidCallback type is a special kind of Function that takes no arguments and has a void return type and it can be defined in the following way using typedef:

 typedef​ VoidCallback = ​void​ Function();

If you wanted to define a callback of a different type that takes some sort of arguments, you’d write the following:

 typedef​ IntFunctionCallback = ​int​ Function(​int​ n);

or the following very common mathematical definition of a real function of a real variable:

 typedef​ RealFunctionOfARealVariable = ​double​ Function(​double​ n);

Definitions can be type-independent (this kind of syntax can be used with anything in Dart):

 typedef​ OneArgumentCallback<T> = T Function(T a);

After defining such a type or just using the generic Function type, we can create functions just like we create variables. For example, if we wanted to recreate in Dart equivalent the f(x) = ex exponential function (where e is Euler’s number, better known in some countries as Napier’s number), we would write the following, using pow and e from dart:math:

 RealFunctionOfARealVariable f = (x) => pow(e, x);
 
 
 assert​(f(2) == pow(e, 2));
 assert​(f(1) > 2.71 && f(1) < 2.72);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset