【问题标题】:How to Refactor a Function in Flutter如何在 Flutter 中重构一个函数
【发布时间】:2021-11-23 19:40:07
【问题描述】:
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 outlineButton , 怎么可能重构一个函数

【问题讨论】:

    标签: flutter dart refactoring flutter-test dart-null-safety


    【解决方案1】:

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

    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)),
      );
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        像这样创建函数

        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*);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-17
          • 2020-10-06
          • 1970-01-01
          • 2010-09-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多