'Why is dart forcing me use const
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.
Solution 1:[1]
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!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamza |
