Difference Between var & dynamic keywords in dart

Jinali GhoghariJinali Ghoghari
1 min read

Table of contents

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.

0
Subscribe to my newsletter

Read articles from Jinali Ghoghari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jinali Ghoghari
Jinali Ghoghari