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,),),],
2
Answers
Remove the const keyword from the constructor:
Given your code for
MyButton
is this:Based on your comments, I’m assuming this is how you’re taking an instance of the
MyButton
widget:Note that you should NOT use
const
keyword in front of theMenuButton
line. This is because you’re assigning a function to theonTap
parameter, which is not a compile-time constant.If you don’t use a
const
right in front of theMenuButton
, you might be usingconst
keyword in parent widget’s constructor. Please remove that to fix the issue.For example:
Hope this helps 🙂