Dynamic Typing - 'var' vs 'dynamic' in Google Dart

Dynamic, Google, Google Flutter, Typing -

Dynamic Typing - 'var' vs 'dynamic' in Google Dart

Interchangeable Most of the Time

You can define untyped variables by declaring them using the ‘var’ or ‘dynamic’ keywords.

  • The ‘var’ keyword declares a variable without specifying its type, leaving the variable as a dynamic.
    • No type is specified.
  • The ‘dynamic’ keyword declares a variable of the type ‘dynamic’ with optional typing.
    • It marks variable as 'not type checked'.

Exception (Methods)

Methods need to return a type so they will work with 'dynamic' but  wont work with 'var':

void main() {

  print (multiplyMethod1(2,4));

  print (multiplyMethod2(2,4));

}

 

dynamic multiplyMethod1(int a, int b){

  return a * b;

}

 

var multiplyMethod2(int a, int b){

  return a * b;

}

 

Error compiling to JavaScript: main.dart:10:1: Error: The return type can't be 'var'. var multiplyMethod2(int a, int b){ ^^^ Error: Compilation failed.