What is a variable in Dart?

variables are used to store the value at the memory location. It contains a 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 variable name. 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 built type or custom type

The following are built primitive types.

Here is an example of 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. The 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, declare a variable with String type and assign it a value.

Default value for the 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 variable scopes.

  • Global Variable
  • Local Variable