I'm developing a mobile app in Flutter and have encountered a problem while trying to pass a function as a parameter to a widget.
To be more precise:
class Test extends StatefulWidget {
final Function(bool) onChanged;
const Test({Key key, this.onChanged}) : super(key: key);
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
bool switchValue = false;
@override
Widget build(BuildContext context) {
return Container(
child: Switch(
value: switchValue,
onChanged: (bool value) {
setState(() => switchValue = value);
widget.onChanged(value);
}));
}
}
It throws NoSuchMethodError: "The method 'call' was called on null" when the widget is used without defining onChanged function. How to define a default function for onChanged parameter? The parameter should be optional. I have tried with:
Solutions without using default value are:
Any suggestions would be appreciated.
You can define a default function like this.
void emptyFunction(bool value) {
if (value) {
// do something
} else {
// do something
}
}
const Test({Key key, this.onChanged = emptyFunction}) : super(key: key);
you can check a sample code showing this in action on dartpad. https://dartpad.dev/30fc0fdc02bec673779eebc733753c05
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.