Home > Software design >  Flutter null safety on class constructors
Flutter null safety on class constructors

Time:01-18

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!

CodePudding user response:

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

CodePudding user response:

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.

  • Related