Difference Between var & dynamic keywords in dart
Table of contents
Certainly! In simple terms:
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.
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.
Subscribe to my newsletter
Read articles from Jinali Ghoghari directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by