The difference between the const keyword and the final keyword underlying the Dart core language

Note: not until the last moment, do not give up, whether the outcome is successful or not, as long as you have struggled, tried to, all have a clear conscience


This article describes how to use the const keyword and the final keyword in Dart

** You might need
CSDN Netease Cloud classroom tutorial
The Denver nuggets EDU College Courses
zhihu Series of articles on Flutter
The headline synchronization Baidu synchronization

This article was first published in the wechat public account (Biglead) about my big front-end career, and published in various technical forums simultaneously.


1 Const, final usage scenarios

1.1 the final

Final is used to modify variables that can only be assigned once, at run time, when the program executes the code.

As shown in the following figure, when final is used ina class, you must initialize a variable when it is declaredWhen final is used to modify a variable ina StatefulWidget:In this case, variables decorated with final may appear to be uninitialized, but it does not violate the understanding that variables decorated with final are assigned at run time, because final variables are only assigned when the defined StatefulWidget is initialized, and of course, once.

The conclusion is that final can be used to modify variables. The modified variable is assigned at run time and can only be assigned once, so the modified variable content is also called a constant.

The core idea is: assign at run time and can only be assigned once


1.2 Use scenarios for const

Const can be used to modify a variable, or a constant constructor, that can be assigned only once.

A variable that can be modified by const can be assigned only once. A variable that can be modified by const is immutable for the lifetime of both the compiler and the application, and is created only once in memory, with the object created the first time reused for each subsequent call.

/// global constant declaration
const String name = "Zhang";

class TestPage2 {

  The class constant specification requires the static modifier to be used
  static const String name = "Zhang";

  void test(a){
    /// method block constants
    const  String name = "Zhang"; }}Copy the code

Const can be used to modify constant constructors and is often used to define enumerated types, as shown in Listing 1-2-1 below

/// Listing 1-2-1
/// Order type
class OrderStatus {

  static const OrderStatus notDeliver = const OrderStatus("To be shipped".1);
  static const OrderStatus hasBeenShipped = const OrderStatus("Shipped".2);
  static const OrderStatus haveTheGoods = const OrderStatus("Received".2);
  
  const OrderStatus(this.statusName,this.statusNumber);

  final String statusName;
  final int statusNumber;
}
Copy the code

Use the code shown in Listing 1-2-2 below

/// Listing 1-2-2
class TestClass5{

  /// determine the order type
  void test(OrderStatus orderStatus){

    switch (orderStatus) {
      case OrderStatus.notDeliver:
        break;
      case OrderStatus.hasBeenShipped:
        break;
      case OrderStatus.haveTheGoods:
        break;
      default:
        break; }}}Copy the code

2 Differences between final and const

2.1 The timing of final and const variables is different

Different timing means that const variables are fixed at compile time, whereas final variables are fixed at run time.

Variables that are const are defined at compile time before the program is run.

The value of a constant decorated with const must be computable at compile time. Values that need to be retrieved at run time are not modifiable, as shown below:

2.2 Different application categories

Final can only be used to modify variables, and the const keyword can also be used to modify constant constructors

2.3 Different Objects are created for the same content

In listing 2-3-1, we create two objects, list1 and list2, but they are identical and const, so they refer to the same object: list1 and list2

  /// Listing 2-3-1
  /// unit tests
  test("Test 1", () {
    
    const List<int> list1 = [1.2.3];
    const List<int> list2 = [1.2.3];

    // The output is true compared to the pointer pointer
    print(list1 == list2);

    // If the output is true, the comparison pointer points to and also compares content
    print(identical(list1, list2));

  });
Copy the code

As shown in Listing 2-3-2, variables declared by final, even if the contents are the same, are recreated:

  /// Code listing 2-3-2
  /// unit tests
  test("Test 2", () {
    final List<int> list1 = [1.2.3];
    final List<int>  list2 = [1.2.3];

    // The output is false to compare pointer pointing
    print(list1 == list2);

    // If the output is false, the comparison pointer points to and also compares content
    print(identical(list1, list2));


  });
Copy the code