What is a variable in Dart?

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

Variables can be declared multiple ways

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

type variableName;
var variable=value;

First one, is an type of an variable must be declare with variablename. Type can be primitive or custom types declared in Dart.

Syntax: Single variable declaration syntax

type variableName;

Multiple variables can be declared with separator comma(,)

type variableName;

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

It can be In built type or custom type

Following are built primitive types.

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

Here is an example for declare variables in multiple ways

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

first variable is declare and initialized with stringvalue. Dart compiler checks the right hand value type, here is string type, variable is infer this type as a string type.

Second way, declared a variable with String type and assigned with a value

Default value for variable

variables declared without initialized has a default value of null.

Variable scopes

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

There are two types of variables scopes

  • Global Variable
  • Local Variable