Difference Between var & dynamic keywords in dart

Difference Between var & dynamic keywords in dart

Table of contents

No heading

No headings in the article.

Certainly! In simple terms:

  1. var in Dart:

    • Use var when you want the Dart compiler to figure out and set the type of a variable based on the value it is assigned.

    • The type is determined at compile-time and remains fixed once assigned.

Example:

    dartCopy codevar myNumber = 42; // Dart knows myNumber is an int.
  1. dynamic in Dart:

    • Use dynamic when you want a variable whose type can change at runtime.

    • It provides flexibility but sacrifices some of the safety checks that Dart's static typing offers.

Example:

    dartCopy codedynamic myDynamicVar = "Hello"; // Dart allows myDynamicVar to change type later.

In essence, var is for static type inference at compile-time, while dynamic is for dynamic typing at runtime. Use var when you know the type at compile-time, and use dynamic when you need more flexibility with types, but be cautious as it can lead to runtime errors.