Search code examples
flutterdartnavigator

I am passing anonymous function with Navigator.pushNamed in its body, but it is showing the error - setState() or markNeedsBuild() called during build


This is the block of code causing error, if I remove Navigator.pushNamed from the function, no error occurs

 RoundedButton(buttonColor: Colors.lightBlueAccent,buttonText: 'Log In',
                onPress: (){Navigator.pushNamed(context, LoginScreen.id);}, <-- This line is causing error
            ),

This is the code for RoundedButton

class RoundedButton extends StatelessWidget {
  RoundedButton({required this.buttonColor, required  this.buttonText, required this.onPress});

  final Color buttonColor;
  final String buttonText;
  final Function onPress;

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

This is the error I am getting The following assertion was thrown building RoundedButton(dirty): setState() or markNeedsBuild() called during build. and The widget which was currently being built when the offending call was made was: RoundedButton dirty The relevant error-causing widget was: RoundedButton RoundedButton:file:///D:/Flutter%20Projects/flashchat/lib/screens/welcome_screen.dart:86:13

I need to navigate to loginscreeen when the button is pressed but the Navigator is causing error inside the function. I tried putting it inside another function but that too is throwing the same error. Don't know how to navigate to the other screen.

I am following Angela Yu's course and in that it is working absolutely fine. I am runing Flutter version 3.3.10 on Windows 10


Solution

  • Use VoidCallback instead of type Function final Function onPress; -> final VoidCallback onPress;