Table of contents
What is Var Keyword in Dart?
The var
keyword in Dart is like a shortcut for declaring variables when you're too lazy to tell Dart exactly what type the variable is. Dart looks at the value you assign to the variable and figures out the type for you.
Example:
var age = 25; // Dart knows age is an integer.
var message = "Hello"; // Dart knows message is a string.
When to Use:
Use
var
when it's clear what type the variable should be based on its initial value.It's handy for making code shorter and cleaner.
When Not to Use:
Don't use
var
when the type isn't clear or might change.If you're writing code that others will use, it's often better to be more explicit about the variable types.
So, var
is like asking Dart to do the typing for you when it's obvious what type the variable should be.