Dart| Flutter: Difference between dynamic vs object with examples

dynamic and object are two predefined types in Dart

dynamic is a dynamic type that accepts any type of value and disables type checking The object is a type that accepts any non-nullable types.

This tutorial explains the difference between dynamic and object types in dart

Difference between Dynamic and Object

Let’s see the difference between dynamic and object with examples.

Dynamic variables can be assigned with any type of value, and these variables can be assigned to any type of variable.

void main() {
  //dynamic variable assigned with string first
  dynamic name = "john";

// you can assign dynamic variable to any variable
  String fname = name;
}

With an object, You can declare a variable of any data.

You need to typecase when these variables are assigned to another type of variables

Below example, Since an int value is a subtype of an object, You can declare and assign an int value. Declared an int variable, assigned with object variable using typecase as a recommended approach

void main() {
  Object age = 25;

  int age1 = age as int;

}
  • Null values

Dynamic variables can be null, Object variables can not be null

main() {
  dynamic str = null; // no errors
  Object obj = null; // Compile time error
}
  • Accessing methods and properties

When you create an instance of employee class with a dynamic type, you are able to access the methods and properties. The same does not work, not accessible methods and properties

class Employee {
  printEmp() => print("Employee Object");
}

void main() {
  dynamic a = new Employee();
  Object b = new Employee();
  a.printEmp(); // No error
  b.printEmp(); // Compile error
}