There are a few predefined types that already exist.
VoidCallback
If you want to create a parameter something like this:
onPressed: () { },
Then you can define it in your class like so:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onPressed}) : super(key: key);
final VoidCallback onPressed;
// ...
}
Notes
The typedef
is defined in the source code like this:
typedef VoidCallback = void Function();
The asynchronous version is AsyncCallback
.
typedef AsyncCallback = Future<void> Function();
ValueSetter
If you want to create a parameter something like this:
onPressed: (value) { },
Then you can define it in your class like so:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onPressed}) : super(key: key);
final ValueSetter<String> onPressed;
// ...
}
Notes
The typedef is defined in the source code like this:
typedef ValueSetter<T> = void Function(T value);
If you want to specify that the function only gets called when there is a change then use ValueChanged instead.
typedef ValueChanged<T> = void Function(T value);
The asynchronous version is AsyncValueSetter
.
typedef AsyncValueSetter<T> = Future<void> Function(T value);
ValueGetter
If you want to create a parameter something like this:
onPressed: () => value,
Then you can define it in your class like so:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onPressed}) : super(key: key);
final ValueGetter<String> onPressed;
// ...
}
Notes
The typedef is defined in the source code like this:
typedef ValueGetter<T> = T Function();
The asynchronous version is AsyncValueGetter
.
typedef AsyncValueGetter<T> = Future<T> Function();
Define your own type
As you can see from all of the examples above, everything is just a typedef
for a Function
. So it is easy enough to make your own.
Say you want to do something like this:
onEvent: (context, child) => value,
Then you would make the typedef like this:
typedef MyEventCallback = int Function(BuildContext context, Widget widget);
And use it like this:
class MyWidget extends StatelessWidget {
MyWidget({Key key, this.onEvent}) : super(key: key);
final MyEventCallback onEvent;
// ...
}
See the documentation for more.