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

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

提交回复
热议问题