What is a variable in Dart?

variables are used to store the value at the memory location. It contains namespace referring to memory location. Declaration

Variables can be declared in multiple ways

You can use using var keyword or directly use the type without the var keyword Syntax:

type variableName;
var variable=value;

The first one is a type of variable that must be declared with a variablename. Type can be primitive or custom types declared in Dart.

Syntax: Single variable declaration syntax

type variableName;

Multiple variables can be declared with a separator comma(,)

type variableName;

type is a datatype of a variable value to store it.

It can be In built type or custom type

The following are built primitive types.

  • number types: Numerical values such as num,int,double
  • string : String of values
  • bool: a true or false values
  • dynamic:
  • list:
  • map:
  • set:

Here is an example for declaring variables in multiple ways

void main() {
  // declare using var
  var str = "welcome";
  //declare using type
  String str2 = "hello";
}

the first variable is declared and initialized with stringvalue. Dart compiler checks the right-hand value type, here is a string type, and the variable has inferred this type as a string type.

The second way, declared a variable with String type and assigned it with a value

Default value for variable

variables declared without initialization have a default value of null.

Variable scopes

Each Variable declared in dart has scope and scope is lifetime based on the place of declaration.

There are two types of variables scopes.

  • Global Variable
  • Local Variable