The method 'call' was called on null. Flutter

271

You are calling the function when you are passing it to the onClick parameter. Instead, just pass the reference to the function.

CustomBtn(
    btext: '8',
    color: Colors.grey[600],
    textColor: Colors.grey[50],
    onClick: buttonPressed,
),
Share:
271
Sameer
Author by

Sameer

Updated on December 22, 2022

Comments

  • Sameer
    Sameer 11 months

    I'm building a calculator in flutter, I am trying to pass a callback onclick function with a parameter to the button widget which is in a different file but when I click any button it throws an exception that method was called on null. Also I dont know how to declare a function with a parameter in the CustomBtn class.

    This is the main widget where I pass the function:

    CustomBtn(
                  btext: '8',
                  color: Colors.grey[600],
                  textColor: Colors.grey[50],
                  onClick: buttonPressed('8'),
                ),
    

    This is the button widget:

      class CustomBtn extends StatelessWidget {
      final String btext;
      final color;
      final textColor;
      final Function onClick;
    
      CustomBtn({
        this.btext,
        this.color,
        this.textColor,
        this.onClick,
      });
      @override
      Widget build(BuildContext context) {
        return RaisedButton(
          child: Text(
            btext,
            style: TextStyle(fontSize: 35.0, color: textColor),
          ),
          onPressed: () => onClick(btext),
          color: color,
          padding: EdgeInsets.fromLTRB(0.0, 24.0, 0.0, 24.0),
        );
      }
    }