flutter - 尝试从子小部件调用 setState 时未调用回调函数

flutter - callback function not called while trying to call setState from child widget

我正在使用 VoidCallback 从子窗口小部件调用 setState。但是回调函数根本没有执行。

下面是我的代码。

子控件:

class TextFormMentorHashtag extends StatefulWidget {
  const TextFormMentorHashtag({Key? key, required this.callback}) : super(key: key);

  final VoidCallback callback;

  @override
  _TextFormMentorHashtagState createState() =>
      _TextFormMentorHashtagState();
}

class _TextFormMentorHashtagState extends State<TextFormMentorHashtag> {

  @override
  Widget build(BuildContext context) {
  ...
    TextFormField(
      ...
      onChanged: (value) {
        if(_formKey.currentState!.validate()) {
          ...
          print('call callback');
          widget.callback;
        }
      }
    )
  }
}

父小部件:

class ApplyMentorPage extends StatefulWidget {
  const ApplyMentorPage({Key? key}) : super(key: key);

  @override
  State<ApplyMentorPage> createState() => _ApplyMentorPageState();
}

class _ApplyMentorPageState extends State<ApplyMentorPage> {

  ...
  bool _disabled = true;

  @override
  Widget build(BuildContext context) {

    void callback() {
      print('callback called');
      setState(() {
        _disabled = !_mentorProvider.check();
      });
    }

    return Scaffold(
      ...
      child: Column(
        children: [
          TextFormMentorHashtag(callback: callback), 
          ...

// _disabled turns submit button on and off in the later code

当我 运行 编码并按下子窗口小部件终端时,打印 'call callback' 但没有 'callback called'。我错过了什么?

如果您使用 TextFormField,它也有 ontap

TextFormField(
  onTap: () {
    print("am called");
  }
)

所以你可能会是这样的

TextFormField(
  onTap: widget.calback
)

您没有在 _TextFormMentorHashtagState 中调用 callback。您应该将其命名为 widget.callback()widget.callback.invoke().

完整代码:

class _TextFormMentorHashtagState extends State<TextFormMentorHashtag> {

  @override
  Widget build(BuildContext context) {
  ...
    TextFormField(
      ...
      onChanged: (value) {
        if(_formKey.currentState!.validate()) {
          ...
          print('call callback');
          // or widget.callback()
          widget.callback.invoke();
        }
      }
    )
  }
}