What I have understood from the sources on the internet is that VoidCallback() is function which takes no parameters and returns no parameters. The following code is from an application and the application is working perfectly, I want to ask that what are the reasons to use VoidCallback as a type and not as a function ?
I am an absolute beginner in Flutter Development, please guide me.
class LoginPage extends StatefulWidget {
final BaseAuth auth;
final VoidCallback onSignedIn;
LoginPage(this.auth);
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return (_LoginPageState());
}
}
VoidCallback IS void Function:
typedef VoidCallback = void Function();
VoidCallback is function which takes no parameters and returns no parameters
Function is base class for all function types.
So technically you could do
//instead of
final VoidCallback onSignedIn;
// could call this
final Function onSignedIn;
But if you want to pass Specific functions. Let's say function that don't take any params or return anything, VoidCallback would be better choices as it checks the type.
class A {
final Function function;
A(this.function){
function("test"); // gonna print test
}
}
class B {
final VoidCallback voidCallback;
B(this.voidCallback){
voidCallback(); // gonna run void function
}
}
String getString(String value) {
print(value);
return value;
}
void main() {
A(getString);
B(getString); //The argument type 'String Function(String)' can't be assigned to the parameter type 'void Function()'
}
You can also set up your own function definitions with typedef
Typedefs are used to avoid losing type informations, but VoidCallback doesn't really have anything to lose, but you only know that because it's a VoidCallback. If it was just a Function you could end up trying to get a value from it. It's a utility for us and compiler.
Typedefs provide useful information for both tools and developers.
You can checkout the language tour for more informations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With