Flutter null safety on class constructors

I’m new to Flutter and using the latest version of it.
Null safety keeps bothering me. I tried my best to solve this problem on the internet but couldn’t figure out.

I’ve tried changing ‘navi’ type but the still getting this error on the line ‘onPressed: navi’.

"The argument type ‘Function’ can’t be assigned to the parameter type ‘void Function()?’"

class RoundedButton extends StatelessWidget {
  late Color? color;
  late String? text;
  late Function navi;

  RoundedButton({super.key, this.color, this.text, required this.navi});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 16.0),
      child: Material(
        color: color!,
        borderRadius: BorderRadius.all(Radius.circular(30.0)),
        elevation: 5.0,
        child: MaterialButton(
          onPressed: navi,
          minWidth: 200.0,
          height: 42.0,
          child: Text(text!),
          // style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}


//Using class in the build method looks like this
RoundedButton(
              color: Colors.lightBlueAccent,
              text: 'Log In',
              navi: () {
                Navigator.pushNamed(context, LoginScreen.id);
              },
            )

Thank you in advance!

>Solution :

You can use VoidCallback which is same as void function.

  late VoidCallback navi;

And instead of late, you can make it final

class RoundedButton extends StatelessWidget {
  final Color? color;
  final String? text;
  final VoidCallback navi;

 const  RoundedButton({super.key, this.color, this.text, required this.navi});

Leave a Reply