Dart/Flutter:具有动态 onPressed 回调方法的自定义按钮小部件

问题描述 投票:0回答:1

我有以下场景:我想使用位于单独文件中的自定义 ButtonWidget。对于提取的 Button,我想移交在 onPressed 参数中使用的不同方法。以下是一些代码片段:

class DialogExample extends StatelessWidget {
  const DialogExample({super.key});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextButton(
          onPressed: () => myShowDialog(context), // works
          child: const Text('Show Dialog'),
        ),
        MyButton(receivedFunction: myShowDialog), // doesn't work
      ],
    );
  }

  // The Method to be passed as an argument
  Future<String?> myShowDialog(BuildContext context) {
    return showDialog<String>(
      // geht auch im Text ohne Typisierung
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => AlertDialog(
        title: const Text('AlertDialog Title'),
        content: const Text('AlertDialog description'),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.pop(context, 'Cancel'),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, 'OK'),
            child: const Text('OK'),
          ),
        ],
      ),
    );
    
  }
}

带有自定义按钮的文件:


class MyButton extends StatefulWidget {
  Future<String?> Function(BuildContext context) receivedFunction;


  MyButton({super.key, required this.receivedFunction});

  @override
  State<MyButton> createState() => _MyButtonState();
}


class _MyButtonState extends State<MyButton> {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
        onPressed: widget.receivedFunction, // here I get a red underline with the error below. 
        child: Text("Externer Button"),
      ),
    );
  }
}



我收到错误:参数类型“Future Function(BuildContext)”无法分配给参数类型“void Function()?”。

flutter dart callback widget custom-widgets
1个回答
0
投票

onPressed
参数需要一个
void Function()
类型的参数,这与
receivedFunction
的类型不同。您可以传递一个匿名方法,该方法使用
receivedFunction
参数来调用
context

onPressed: () => widget.receivedFunction(context);
© www.soinside.com 2019 - 2024. All rights reserved.