Variables in Dart

Variables

Variables are containers used to store value in the program. There are different types of variables where we can store different types of values. Here is an example of creating a variable and initializing it.

// here variable name contains value John.
var name = "John";

Types Of Variables

They are called data types. We will learn more about data types later in this dart tutorial.

  • String: For storing text value. E.g. “John” [Must be in quotes]
  • int: For storing integer value. E.g. 10, -10, 8555 [Decimal is not included]
  • double: For storing floating point value. E.g. 10.0, -10.2, 85.698 [Decimal is included]
  • num: For storing any types of number. E.g. 10, 20.2, -20 [both int and double]
  • bool: For storing true or false value. E.g. true, false [Only stores true or false values]
  • var: For storing any value. E.g. ‘Bimal’, 12, ‘z’, true

Syntax

type variableName = value;

Example

 void main() {
//Declaring Variables
String name = "John";
String address = "USA";  
num age = 20; // used to store any types of numbers 
num height = 5.9;
bool isMarried = false;
   
// printing variables value   
print("Name is $name");
print("Address is $address");
print("Age is $age");
print("Height is $height");
print("Married Status is $isMarried");
}
Show Output
Info

Note: Always use the descriptive variable name. Don’t use variable name like a, b, c because this will make your code more complex.

Rules For Creating Variables In Dart

  • Variable name can consist of letters and alphabets.
  • Keywords are not allowed to use as a variable name.
  • Blank spaces are not allowed in a variable name.
  • The first character of the variable should always be alphabet and cannot be a digit.
  • Variable names are case sensitive i.e. a and A are different.
  • Special characters are not allowed except for the underscore (_) and the dollar ($) sign.

Constant In Dart

Constant is the type of variable whose value never changes. In programming, changeable values are mutable and unchangeable values are immutable. In some situations, you don’t need to change the value once declared. Like the value of PI=3.14, never changes. To create a constant in dart you can use the const keyword.

void main(){
const pi = 3.14;
pi = 4.23; // not possible  
print("Value of PI is $pi");
}
Show Output