简体   繁体   中英

Flutter Error String Function() can't be assigned to a variable of type 'String'

I have a widget which has String Function() validation as one of its properties.

The widget looks something like

MyWidget(validation: () {
      if (text.isEmpty) {
        return "Text is required";
      }  else {
        return null;
      }
    },
  );

The problem is when i try to access MyWidget.validation i am expecting it to give me the string but i get an error which says A value of type 'String Function()' can't be assigned to a variable of type 'String'.

Can someone please show me a way out? Thanks

Assuming your widget looks like this:

class MyWidget extends StatelessWidget {
  final ValueChanged<String> validation;

  const MyWidget({Key key, this.validation}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SomeWidget();
  }
}

This should now work:

MyWidget(
  validation: (text) {
    if (text.isEmpty) {
      return "Text is required";
    } else {
      return null;
    }
  },
);

Access MyWidget.validation() Instead.

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