What is the difference between the “const” and “final” keywords in Dart?

前端 未结 11 1333
温柔的废话
温柔的废话 2020-11-27 10:52

What is the difference between const and final keyword in Dart?

11条回答
  •  天涯浪人
    2020-11-27 11:13

    my understand

    const means its initial value is must be fixed, can not be a dynamic value;

    final means its initial value is must be fixed but can be a dynamic value, equal to the var with a fixed value.

    code demos

    void main() {
      const sum = 1 + 2;
      // const can not change its value
      print("sum = ${sum}");
      // Const variables must be initialized with a constant value.
      const time = new DateTime.now();
      // Error: New expression is not a constant expression.
      print("time = ${time}");
    }
    
    
    // new DateTime.now();
    // dynamic timestamp
    
    void main() {
      final sum = 1 + 2;
      // final can not change its value
      print("sum = ${sum}");
      final time = new DateTime.now();
      // final === var with fixed value
      print("time = ${time}");
    }
    

    refs

    https://dart.dev/guides/language/language-tour#final-and-const

提交回复
热议问题