Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
like image 688
shalevB Avatar asked Dec 04 '25 06:12

shalevB


2 Answers

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
      ),
    );
  }
}
like image 93
lakscastro Avatar answered Dec 07 '25 00:12

lakscastro


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,
      ),
    );
  }
}
like image 44
MD KAMRUL ISLAM Avatar answered Dec 07 '25 01:12

MD KAMRUL ISLAM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!