Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()?’"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading