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:
int
– used to store integers.
var age = 30;
int distance = 50;
double
– used to store floating-point numbers.
var height = 5.8;
double price = 10.5;
String
– used to store text values.
dartCopy codevar name = 'John';
String message = 'Hello, World!';
bool
– used to store true/false values.
var isStudent = true;
bool isTall = false;
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];
Map
– used to store key-value pairs.
var person = {'name': 'John', 'age': 30};
Map<String, int> scores = {'Math': 90, 'Science': 80};
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.
Check Also : How to get Element at specific Index from List in Dart
Check Also : Geolocator Package in flutter : How to implement it
Read more updates related to flutter at flutterfever.com.