[Dart] Final vs. Const

 

[Ko]

 - instance variable = field = property

 - 불변의 상수를 의미하는 keyword이지만 Const 더욱 불변의 강도가 강하다. Const app lifecycle에서 절대 변치 않음을 의미하기 때문에 색상, 글자 크기 등이 고정일 변수의 앞에 const 붙여주어야 flutter build method 부분을 rebuild 하지 않게되어 app 속도가 빨라짐. final 기본적으로 고정 상수이기는 하지만, 상황에 따라 변할 있는, , 주로 constructor에서 설정되어야 하는 변수 등의 앞에 주로 선언해주어야 . final widget 생성되는 시점마다는 변경될 있지만 생성된 위젯내에서의 const 상수는 변경할 없음을 의미함. Stateless widget 대표적이 예이며, 위젯은 자체적으로 상태를 가지지 않기 때문에 다른 속성을 가지는 stateless widget으로 바꾸려면 constructor 새로운 property 값을 전달하면서 새로운 위젯을 만들어야 . 이때 사용되는 것이 const variable. Stateless widget 모든 propertyconst variable.

 - final variable run-time constant이며, 1회만 설정할 있고, const variable compile-time constant. , final app build시에는 값이 정해지지 않으며, app 실행과정에서 값이 정해지고, const app build 값이 정확히 정해져야 . 예를들면 DateTime.now() 같은 경우는 app 실행시 정해지는 값이므로 const 변수에는 담길 없고 final 변수에 담겨져야 . Device size 등도 마찬가지.

 

[En]

 - instance variable = field = property

 - Both are keywords that mean constants, but Const has more constant strength. Const means that it never changes in the app's lifecycle, so when color, font size, etc. are fixed, you must put const in front of the variable, so the flutter build method does not rebuild that part, so the app speeds up. final is basically a fixed constant, but it must be declared in front of variables that can be changed depending on the situation, that is, variables to be set in the constructor. final means that the widget can be changed every time the widget is created, but the const constant in the widget once created cannot be changed. Stateless widget is a typical example, and since this widget does not have its own state, to change to a stateless widget with other properties, you must create a new widget by passing a new property value to the constructor. The const variable used at this time All properties of stateless widgets are constant variables.

 - The final variable is run-time constant, can be set only once, and the const variable is compile-time constant. In other words, the final value is not determined during app build, the value is determined during app execution, and the const value must be accurately determined during app build. For example, DateTime.now () is a value that is determined when the app is executed, so it cannot be contained in the const variable, but must be contained in the final variable. Device size and so on.

'플러터(Flutter) > 다트(Dart)' 카테고리의 다른 글

[Dart] Functions as First Order Objects  (0) 2020.03.19
[Dart] Enums  (0) 2020.03.19
[Dart] Class Constructors  (0) 2020.03.18
[Dart] OOP : Object Oriented Programming  (0) 2020.03.18
[Dart] Conditionals - If/Else  (0) 2020.03.18

+ Recent posts