[英]How to define a default function with parameters in Dart?
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.我正在 Flutter 中开发移动应用程序,并在尝试将 function 作为参数传递给小部件时遇到问题。
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.当在未定义 onChanged function 的情况下使用小部件时,它会抛出 NoSuchMethodError: "The method 'call' was called on null"。 How to define a default function for onChanged parameter?如何为 onChanged 参数定义默认的 function? 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.您可以像这样定义默认的 function。
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.您可以在 dartpad 上查看显示此操作的示例代码。 https://dartpad.dev/30fc0fdc02bec673779eebc733753c05 https://dartpad.dev/30fc0fdc02bec673779eebc733753c05
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.