简体   繁体   English

如何使用 Dart 中的参数定义默认 function?

[英]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:我尝试过:

  • ( ) { } - A value of type 'Null Function( )' can't be assigned to a variable of type 'dynamic Function(bool)'. ( ) { } - 'Null Function( )' 类型的值不能分配给'dynamic Function(bool)' 类型的变量。
  • (bool) { } - The default value of an optional parameter must be constant. (bool) { } - 可选参数的默认值必须是常量。

Solutions without using default value are:不使用默认值的解决方案是:

  • to check if onChange parameter is not null before calling it, or在调用它之前检查 onChange 参数是否不是 null,或者
  • to define it every time when the widget is used - onChanged: (bool val) { }每次使用小部件时定义它 - onChanged: (bool val) { }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM