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:
- ( ) { } - A value of type 'Null Function( )' can't be assigned to a variable of type 'dynamic Function(bool)'.
- (bool) { } - The default value of an optional parameter must be constant.
Solutions without using default value are:
- to check if onChange parameter is not null before calling it, or
- to define it every time when the widget is used - onChanged: (bool val) { }
Any suggestions would be appreciated.