繁体   English   中英

如何在 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 的轮廓按钮,怎么可能重构一个函数

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

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()一种奇特方式。 除了,它不包含任何空格,你可以在这里看到。 所以就这样声明吧。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM