In the 'Write Your First App' tutorial on the Flutter docs, Step 4 titled "Step 4: Create an infinite scrolling ListView", you are asked to create 2 variables show here:
class RandomWordsState extends State<RandomWords> {
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18.0);
...
}
Why is the const
keyword used in the 3rd line? I come from a C# and JavaScript background and I'm not used to seeing this on the right side of an assignment statement. I notice if I remove it it still works as I expected. Could you please explain in lamens terms why this is being used and when should I do the same? I'm guessing it's overkill and I don't have to use it but I just want to make sure.
I do not believe this is a duplicate because the answer in this post was perfect in explaining my question and not found in the other post, not to mention the other post is a two part question that nobody would find when using google.
From dart news website:
"
const
" has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, likeconst [1, 2, 3]
, and when constructing objects (instead of new) likeconst Point(2, 3)
. Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.
Read more here.
In my words, you can use const
constructor(constructors that defined as const
) like const Text()
or new Text()
.
If you use const Text()
: This will allocate only one memory space and when you are add another const Text()
, that will reuse the same object but the new Text()
will always allocate new memory space. So, using const
you can increase your program performance(not that much performance but less memory allocation). Also, you can define your class constructors as const
, if it need to reuse.
I notice if I remove it it still works as I expected.
That because with Dart two new
and const
keyword optional when you are creating object/instance, that will handle by the Dart VM. Initially there was some problems but those are fixed now.
Even if you avoid const
/new
those will added by the Dart VM. The reason for to made those two keyword optional is in Flutter you have to type those two everywhere(ex: in widget tree).
Dart two enhancement() Feb 23
Here's another question with some answers that might help.
What color system does flutter use and why do we use `const Color` instead of `new Color`
As explained by the accepted answer, const constructors are a small optimization. In dart a const MyObject(42) will only be allocated once even when you call it hundreds of time. Which means less memory allocation > faster
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With