Context: Not a constant expression, error on dart
I was following a udemy course but I got stuck I got this error which I don't know why it ocurres
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
VoidCallback selectHandler;
Answer(this.selectHandler);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: const RaisedButton(
color: Colors.blue,
child: Text('Answer 1'),
onPressed: selectHandler,
),
);
}
}
onPressed: selectHandler,
this line it the problematic one.
I tried removing random keyword but i really don't know what to do.
that's the error log
lib/answer.dart:15:20: Error: Not a constant expression.
onPressed: selectHandler,
^^^^^^^^^^^^^
lib/answer.dart:12:20: Error: Constant evaluation error:
child: const RaisedButton(
^
lib/answer.dart:15:20: Context: Not a constant expression.
onPressed: selectHandler,
You can't put functions inside const
expressions, just remove the const
keyword from:
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
VoidCallback selectHandler;
Answer(this.selectHandler);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: /* const -> Remove this const keyword */ RaisedButton(
color: Colors.blue,
child: Text('Answer 1'),
onPressed: selectHandler, // This is not a constant because the compiler can't assign the value at the compile time, so we can't use that in a const expression
),
);
}
}
You used const before RaisedButton when calling a variable inside the onPressed Function. Try removing the const keyword from the RaisedButton. It should work that way.
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
VoidCallback selectHandler;
Answer(this.selectHandler);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: const RaisedButton(
color: Colors.blue,
child: Text('Answer 1'),
onPressed: selectHandler,
),
);
}
}