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

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

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

11条回答
  •  孤街浪徒
    2020-11-27 11:30

    Extending the answer by @Meyi

    • final variable can only be set once and it is initialized when accessed.(for example from code section below if you use the value of biggestNumberOndice only then the value will be initialized and memory will be assigned).
    • const is internally final in nature but the main difference is that its compile time constant which is initialized during compilation even if you don't use its value it will get initialized and will take space in memory.

    • Variable from classes can be final but not constant and if you want a constant at class level make it static const.

    Code:

    void main() {
    
        // final demonstration
        final biggestNumberOndice = '6';
        //  biggestNumberOndice = '8';     // Throws an error for reinitialization
    
        // const
        const smallestNumberOnDice = 1;
    
    }
    
    class TestClass {
    
        final biggestNumberOndice = '6';
    
        //const smallestNumberOnDice = 1;  //Throws an error
        //Error .  only static fields can be declared as constants.
    
        static const smallestNumberOnDice = 1;
    }
    

提交回复
热议问题