Home > OS >  How to Refactor a Function in Flutter
How to Refactor a Function in Flutter

Time:10-03

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

This is my code here I have trying to refactor the onpressed outlinedButton , How can it possible to refactor a function

CodePudding user response:

create function like this

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

now just pass the function you want to call in when onpressed

customOutlinedButton("your function here");

CodePudding user response:

Did you want to fix error?
Here is my refactoring result.

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

CodePudding user response:

The onpressed method accepts a VoidCallBack type, which is just a fancy way of saying void function(). Except, it doesn't contain any space, You can see for yourself here. So declare it like this.

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