Home > Software design >  How to initialise a void function in a class
How to initialise a void function in a class

Time:10-26

I was creating a new class name RoundedButton which is below

class RoundedButton extends StatelessWidget {
  const RoundedButton({required this.colour, required this.title, required this.onPressed});
  final Color colour;
  final String title;
  final Function onPressed;
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        elevation: 5.0,
        color: colour,
        borderRadius: BorderRadius.circular(30.0),
        child: MaterialButton(
          onPressed: onPressed,
          minWidth: 200.0,
          height: 42.0,
          child: Text(
           title,
          ),
        ),
      ),
    );
  }
}

but the onPressed function variable I have created keeps bringing this error every time I use it in the onPressed property of the textfield

The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.

and when I change the onPressed data type to void, it still not working. What have I done wrong in this?

CodePudding user response:

Change the type of onPressed to either VoidCallback or Function().

CodePudding user response:

you can use VoidCallback or void Function()

try this,

class RoundedButton extends StatelessWidget {
  const RoundedButton({
    Key? key,
    required this.colour,
    required this.title,
    required this.onPressed,
  }) : super(key: key);

  final Color colour;
  final VoidCallback onPressed;
  final String title;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        elevation: 5.0,
        color: colour,
        borderRadius: BorderRadius.circular(30.0),
        child: MaterialButton(
          onPressed: onPressed,
          minWidth: 200.0,
          height: 42.0,
          child: Text(
            title,
          ),
        ),
      ),
    );
  }
}
  • Related