Dart Variables | RRTutors

Dart Variables

Variable is named storage location and Data types simply refers to the type and size of data associated with variables and functions.

Dart uses a var keyword to declare the variable. 

The syntax of var is defined below

 

var name = 'Flutter';

 

Dart provide us various built in data types 

Numbers 

As Other Programming languages to Java or C++ Dart does not have anything like float or long. Dart offers just two types of number 

Int 

Double

Strings : It represents a sequence of characters. String values are specified in either

single or double quotes

 

Booleans : Dart uses the bool keyword to represent Boolean values – true and false

Lists & Maps : It is used to represent a collection of objects

Runes : Represents string Unicode coded characters (UTF-32 code points), etc

Symbols : Use a Symbol literal to obtain the symbol's symbol object, which is to add a # symbol in front of the identifier

 

String name = 'Flutter';

 

Here String is Data type, name is variable name and Flutter is value of variable

 

var name = 'Flutter';

 

The type of the name variable is inferred as String. 

The compiler will check we have var keyword not String so type depends on value which in this case is String

 

Example: 

 

void main() {

   String fName = 'Chandu';

  var lName='Mouli';

  int intValue = 123;

  print(fName);

  print(lName);

  print(intValue);

}

Output will be

Chandu

Mouli

123

 

List : Declare a list is very simple, you can simply use square brackets [] to define the list. The following are common operations for lists

 

main(List<String> args) {

  var list = [1,2,3,4];

 

  print(list); //Output: [1, 2, 3, 4]

  //Length 

  print(list.length);

 

  //Selecting single value 

  print(list[1]);    //Output: 2

 

  //Adding a value 

  list.add(10);

 

  //Removing a single instance of value 

  list.remove(3);

 

  //Remove at a particular position 

  list.removeAt(0);

}

 

If we want to define a compile-time constant list, for example, the contents of the list are immutable, you can use keywords const

 

main(List<String> args) {

  var list = const [1,2,3,4];   

}

Advertisements