Difference between “var” and “dynamic” type in Dart?

前端 未结 11 2087
攒了一身酷
攒了一身酷 2021-01-30 10:25

According to this article:

As you might know, dynamic (as it is now called) is the stand-in type when a static type annotation is not provide

11条回答
  •  被撕碎了的回忆
    2021-01-30 10:31

    Both in dynamic and var,the variable can hold data of any data type, i.e., int , float,string,etc

    If a variable is declared as a dynamic and if even initialised, its type can change over time.Try this code in https://dartpad.dev/

    void main() {
      dynamic x = 'abc';
      x = 12345;
      print(x);
    
    }
    

    If you declare variable as a var, once assigned type can not change.

    void main() {
      var x = 'abc';
      x = 12345;
      print(x);
    }
    

    The above code will result in the error stating that A value of type 'int' can't be assigned to a variable of type 'String' - line 3

    BUT, if you state a var without initializing, it becomes a dynamic:

    void main() {
      var x ;
      x = 'abc';
      x=12345;
      print(x);
    }
    

提交回复
热议问题