Home > Back-end >  Context: Not a constant expression, error on dart
Context: Not a constant expression, error on dart

Time:01-14

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,

CodePudding user response:

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
      ),
    );
  }
}

CodePudding user response:

Remove const from RaisedButton and instead make your widget const.

class Answer extends StatelessWidget {
  final VoidCallback selectHandler; // Made final

  const Answer(this.selectHandler); // const added

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: RaisedButton( // const removed
        color: Colors.blue,
        child: Text('Answer 1'),
        onPressed: selectHandler,
      ),
    );
  }
}
  •  Tags:  
  • Related