skip to Main Content

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!

2

Answers


  1. The error does not come from the null-safety though. It should be Function() navi; instead of Function.

    late keyword suggests that the variable has delayed initialization, check here for reference.

    Login or Signup to reply.
  2. 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});
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search