如何在 Flutter 中重构一个函数

How to Refactor a Function in Flutter

import 'package:flutter/material.dart';

Widget justButton({
  String btText = '',
  Color bgColor = Colors.blue,
  Color? txtColor = Colors.white,
  Color borderColor = Colors.black,
  void Function() onpressedAction,//here iam getting problem
}) {
  return OutlinedButton(
    //i wanted to refactor this onpressed 
    onPressed: () {
      print('Go to events Page');
    },
    child: Text(btText),
    style: OutlinedButton.styleFrom(
        backgroundColor: bgColor,
        primary: txtColor,
        side: BorderSide(color: borderColor)),
  );
}

这是我的代码,我试图重构 onpressed outlinedButton , 怎么可能重构一个函数

你想修复错误吗?
这是我的重构结果。

import 'package:flutter/material.dart';

Widget justButton({
  String btText = '',
  Color bgColor = Colors.blue,
  Color? txtColor = Colors.white,
  Color borderColor = Colors.black,
  Function? onpressedAction,//here iam getting problem
}) {
  return OutlinedButton(
    //i wanted to refactor this onpressed 
    onPressed: () => onpressedAction!(),
    child: Text(btText),
    style: OutlinedButton.styleFrom(
        backgroundColor: bgColor,
        primary: txtColor,
        side: BorderSide(color: borderColor)),
  );
}

像这样创建函数

Widget customOutlinedButton(Function? func){
    return OutlinedButton(
        onPressed: func,
        child: Text(btText),
        style: OutlinedButton.styleFrom(
            backgroundColor: bgColor,
            primary: txtColor,
            side: BorderSide(color: borderColor)),
      );
    }

现在只需传递按下时要调用的函数

customOutlinedButton(*your function here*);

onpressed 方法接受 VoidCallBack 类型,这只是 void function() 的一种奇特说法。除此之外,它不包含任何space,您可以自己查看here。所以这样声明。

Widget justButton({
   ....
  VoidCallBack? onpressedAction,
   
}){
return OutlinedButton(
   ....
    onPressed: onpressedAction,
   ....
}