-1

I have this piece of code that intend to use in a stateless widget in flutter.

const String default_question = 'the question';

class Trial {
  final String question;
  const Trial.standard() :
        question = default_question;
}

I use it like this:

final Trial _trial = const Trial.standard();

And this works. But it doesn't work without using const. And I want to understand why const is neccessary here. Because I plan on using a constructor that is not constant in the future.

-----------EDIT---------------

So I had a deeper look into the problem. My IDE linked the error to sauce. Which made me realise that the problem had nothing to do with trial but with the constructor for the stateless widget that I was using. The constructor that I had for the stateless widget was a constant costructor, I think that that is a default configuration voor creating a new stateless widget with my IDE. So I just removed the const keyword there and now I can declare variables in that widget that are not constant.

I'm not sure if a non constant constructor for a stateless widget is bad practice in flutter, but for now it makes sense to me.

Harm
  • 109
  • 9
  • What do you mean by "it doesn't work without using const"? Dart is not *forcing* you to use `const`. The Dart analyzer is providing a *suggestion* to use `const` when possible. – jamesdlin Jan 25 '22 at 17:21
  • Well there was an actual [error](https://dart.dev/tools/diagnostic-messages?utm_source=dartdev&utm_medium=redir&utm_id=diagcode&utm_content=const_constructor_with_field_initialized_by_non_const#const_constructor_with_field_initialized_by_non_const) when I ran the code without const. Dart was forcing me to use const there because I was using a constant constructor in the stateless widget the was using _trial. – Harm Jan 25 '22 at 18:02
  • Yeah, that's a different situation than what you originally described. When you ask questions in the future, include the error message instead of saying "it doesn't work", which provides no useful details. If you want this question to be useful to others, you should update it with the error message and with the proper code context. – jamesdlin Jan 25 '22 at 18:11

1 Answers1

2

cosnt marked widgets or variables are built only once in flutter framework which helps in performance improvement.

And this is done by a packages flutter_lints which is added in pubspec.yaml by default in latest flutter versions. You can check docs at given at flutter official website.

If you don't want to use this thing, simply remove the package from pubspec.yaml

Cheers!

Hamza
  • 1,523
  • 15
  • 33
  • Hi, thanks for your help, it appeared to be a different problem though. But your suggestion helped me for sure. – Harm Jan 25 '22 at 18:04