“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
preface
There are two ways to define constants in Flutter, either final or const. In many articles on performance tuning, it is recommended that subcomponents be declared as const as possible. So, what exactly does const do to optimize performance? In this article we will decrypt the const keyword of Flutter.
The core definition
Variables declared by const are determined at compile time and never change. This means that the compiler knows in advance how to store the value of this variable. For example, the following variable a declared with const is always 1 at compile time.
const int a = 1;
Copy the code
Also, a Flutter can automatically infer the type of variables declared by const.
const name = 'Island code farmer';
Copy the code
So why not use final? Variables declared by final are also immutable. The difference here is that final variables can be assigned after they are declared and cannot be changed after they are assigned. For example, we can declare variables of final type without assigning, or even initialize them via constructors.
final int a;
a = 1;
// constructor
class FinalDemo {
final name;
FinalDemo({required this.name});
}
Copy the code
This indicates that variables declared by final are determined at run time.
What does const mean
In effect, declaring const tells the compiler that the variable will not change for the lifetime of the code, so you only need to create a copy of the variable, and use it everywhere else to refer to that copy instead of creating a new object. Declaring a class constructor const is important for performance in Flutter. When Flutter processes widgets, each Widget is a class. Imagine that we need to create a Widget that never changes, such as a fixed-size blue square:
class BlueSquare extends StatelessWidget {
final double size;
BlueSquare({Key? key, required this.size}) : super(key: key);
Widget build(BuildContext context) {
returnContainer( height: size, width: size, color: Colors.blue, ); }}Copy the code
Suppose that in our application we have 100 blue squares with sides of length 50. If we build our class the way above, that means we will create 100 instance objects of the BlueSquare class.
BlueSquare(size: 50);
Copy the code
This is a huge waste of memory. If you just added a reference every time you created a BlueSquare object of the same size, it would be like fetching a reusable object from the cache. This is the true value of const**! The const declaration tells Flutter that if it encounters an immutable constructor (const constructor), it is an immutable object and can be reused.
A const constructor is a constructor that initializes all of its final fields, declared by prefixing the constructor with const. If you do not prefix a constructor with const, the object will be treated as a mutable object by Flutter, even if it is immutable. For example, BlueSquare in the above example could declare the constructor const and then use const as well.
const BlueSquare({Key? key, required this.size}) : super(key: key);
const BlueSquare(size: 50);
Copy the code
Note that if the constructor is declared const, all fields of the class need to be of final type to ensure that the two objects are consistent at run time. Of course, if the constructor of the declared class is const and the field is not final, the compiler will tell you that there is an error.
Performance optimizations for rendering
The const decoration is not just about saving memory overhead at component build time. When an object is marked as a constant, a Flutter does not rebuild a const component when it needs to. Since the component should not be changed, this reconstruction makes no sense. This can be a huge performance boost for an application’s runtime! Because Flutter knows which components need to be rebuilt and which do not, it can speed up thermal reloading even during thermal reloading. Therefore, if possible, declare your component or class constructors as const and use const qualifiers when using their objects. For example:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'animated',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: constAnimationHomePage(), ); }}class AnimationHomePage extends StatelessWidget {
const AnimationHomePage({Key? key}) : super(key: key);
/ /...
}
Copy the code
conclusion
Hopefully, after reading this article, you will understand the real use of const and review your application code to see if it follows the principle of making component properties final whenever possible, constructors const, and using such component objects as const.
I am dao Code Farmer with the same name as my wechat official account. This is a column about the introduction and practice of Flutter, providing systematic learning articles about Flutter. See the corresponding source code here: The source code of Flutter Introduction and Practical column. If you have any questions, please add me to the wechat account: island-coder. If you feel you have something to gain, please give three pairs of love as follows:
👍🏻 : a praise to encourage!
🌟 : Collect articles, easy to look back!
💬 : Comment exchange, mutual progress!