简体   繁体   中英

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.

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.

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.

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