flutterdartontap

Can't call onTap function


It always appears error below when I run the code. Could anyone give an advice? Thanks.

Error: Not a constant expression.

page.dart

MyButton(text: 'Get Started',onTap: (){Navigator.pushNamed(context,'/menupage');},),

button.dart

class MyButton extends StatelessWidget {final String text;final void Function()? onTap;
const MyButton({super.key,required this.text,required this.onTap,});
@override
Widget build(BuildContext context){
    return GestureDetector(
    onTap: onTap,
    child: Container(
        decoration: BoxDecoration(color: Color.white,),
        padding: EdgeInsets.all(20),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.center
            children: [
                Text(
                    text,
                    style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,),),],

Solution

  • Given your code for MyButton is this:

    
    class MyButton extends StatelessWidget {
      final String text;
      final void Function()? onTap;
      const MyButton({
        super.key,
        required this.text,
        required this.onTap,
      });
      @override
      Widget build(BuildContext context) {
        return GestureDetector(
          onTap: onTap,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
            ),
            padding: const EdgeInsets.all(20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  text,
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        );
      }
    }
    

    Based on your comments, I'm assuming this is how you're taking an instance of the MyButton widget:

      const MyButton(text: 'Get Started',onTap: (){Navigator.pushNamed(context,'/menupage');},);
      ^^^^^
    

    Note that you should NOT use const keyword in front of the MenuButton line. This is because you're assigning a function to the onTap parameter, which is not a compile-time constant.

    If you don't use a const right in front of the MenuButton, you might be using const keyword in parent widget's constructor. Please remove that to fix the issue.

    For example:

      const Row(
      ^^^^^
        children: [
          MyButton(text: 'Get Started', onTap: (){Navigator.pushNamed(context,'/menupage');},),
        ],
      );
    

    Hope this helps :)