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

前端 未结 11 2059
攒了一身酷
攒了一身酷 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:49

    dynamic is a data type that indicates all data types in dart

    var is a variable declaration way like "final" that takes the data type of its value

    0 讨论(0)
  • 2021-01-30 10:50

    A dynamic variable can change his type and a var type can't be changed.

    For example :

    var myVar = 'hello';
    dynamic myDynamicVar = 'hello';
    myVar = 123; // not possible
    myDynamicVar = 123; // possible
    
    0 讨论(0)
  • 2021-01-30 10:56

    dynamic: can change TYPE of the variable, & can change VALUE of the variable later in code.

    var: can't change TYPE of the variable, but can change VALUE of the variable later in code.

    final: can't change TYPE of the variable, & can't change VALUE of the variable later in code.

    dynamic v = 123;   // v is of type int.
    v = 456;           // changing value of v from 123 to 456.
    v = 'abc';         // changing type of v from int to String.
    
    var v = 123;       // v is of type int.
    v = 456;           // changing value of v from 123 to 456.
    v = 'abc';         // ERROR: can't change type of v from int to String.
    
    final v = 123;       // v is of type int.
    v = 456;           // ERROR: can't change value of v from 123 to 456.
    v = 'abc';         // ERROR: can't change type of v from int to String.
    
    0 讨论(0)
  • 2021-01-30 10:56
    var a ;
    a = 123;
    print(a is int);
    print(a);
    a = 'hal';
    print(a is String);
    

    When defined without initial value, var is dynamic

    var b = 321;
    print(b is int);
    print(b);
    //b = 'hal'; //error
    print(b is String);
    

    When defined with initial value, var is int in this case.

    0 讨论(0)
  • 2021-01-30 10:56

    To clarify some of the previous answers, when you're declaring a variable as dynamic, it's type changes depending on what you assign to it. When you're declaring a var, the type is set once it's assigned something, and it cannot be changed after that.

    For example, the following code:

    dynamic foo = 'foo';
    print('foo is ${foo.runtimeType} ($foo)');
    foo = 123;
    print('foo is ${foo.runtimeType} ($foo)');
    

    will return the following result when run in DartPad:

    foo is String (foo)
    foo is int (123)
    

    But the following code won't even compile:

    var bar = 'bar';
    print('bar is ${bar.runtimeType} ($bar)');
    bar = 123; // <-- Won't compile, because bar is a String
    print('bar is ${bar.runtimeType} ($bar)');
    

    Long story short - use dynamic if you want a non-typed variable, use var when you want a typed variable with whatever type you assign to it.

    0 讨论(0)
提交回复
热议问题