Member-only story

FLUTTER INTERVIEW QUESTIONS

What are const objects in Dart?

Jelena Lecic
3 min readDec 30, 2019

--

In one sentence - objects created with const keyword that are being instantiated during compile-time and reused over and over agin.

First Text is going to be created in compile-time and the same instance is going to be used each and every time UI is being rebuilt, and the second Text is a non-const object that is going to be recreated every time program execution reaches its point.

Using const objects can help you save some time(using existing objects instead of creating them) and space(objects with the same values get instantiated only once). So, if you write:

const Text(‘Hello’) 

10 times in your app, you will be reusing the same object - not recreating it each time.

In order to be able to create const objects, you need to use a const constructor:

class Widgy extends StatelessWidget {
const Widgy(this.a);

final int a;

@override
Widget build(BuildContext context) {
return Text('$a');
}
}

But, if you add some non final field in your class, it can no longer have a const constructor:

--

--

Responses (2)