Dart – Variables concept

Variables are used to store values in memory for later use. In Dart, you can declare variables using the var, final, or const keywords. The type of a variable is determined by the value assigned to it. If you use var keyword, the type is inferred automatically by the value assigned to the variable. On the other hand, if you use final or const keyword, the type of the variable must be explicitly specified.

Here are the different types of variables in Dart:

  1. int – used to store integers.
var age = 30;
int distance = 50;
  1. double – used to store floating-point numbers.
var height = 5.8;
double price = 10.5;
  1. String – used to store text values.
dartCopy codevar name = 'John';
String message = 'Hello, World!';
  1. bool – used to store true/false values.
var isStudent = true;
bool isTall = false;
  1. List – used to store a list of values of the same type.
var fruits = ['apple', 'banana', 'cherry'];
List<int> numbers = [1, 2, 3, 4, 5];
  1. Map – used to store key-value pairs.
var person = {'name': 'John', 'age': 30};
Map<String, int> scores = {'Math': 90, 'Science': 80};
  1. dynamic – used to store any type of value.
dynamic value = 'hello';
value = 10;

Here are some examples of how to use variables in Dart:

void main() {
  // Variables
  var name = 'John';
  int age = 30;
  double height = 5.8;
  bool isStudent = true;
  List<String> hobbies = ['reading', 'traveling'];
  Map<String, int> scores = {'Math': 90, 'Science': 80};

  // Printing variables
  print('Name: $name');
  print('Age: $age');
  print('Height: $height');
  print('Is student: $isStudent');
  print('Hobbies: $hobbies');
  print('Scores: $scores');

  // Updating variables
  name = 'Mary';
  age = 25;
  height = 5.5;
  isStudent = false;
  hobbies.add('painting');
  scores['History'] = 85;

  // Printing updated variables
  print('Name: $name');
  print('Age: $age');
  print('Height: $height');
  print('Is student: $isStudent');
  print('Hobbies: $hobbies');
  print('Scores: $scores');
}

In this example, we have declared variables of different types, assigned values to them, and printed their values. We have also updated some of the variables and printed their updated values.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More