Dart Data Types#
Dart is a statically typed language, which means that the type of variable is known at compile time. However, using the dynamic
keyword, Dart can also mimic dynamically typed behavior. Below are the core data types available in Dart.
Basic Data Types#
1. int
#
- Represents whole numbers.
- Examples:
int age = 30;
2. double
#
- Represents 64-bit (double-precision) floating-point numbers.
- Examples:
double height = 1.88;
3. String
#
- Represents a sequence of characters.
- Uses UTF-16 encoding.
- Examples:
String name = "John Doe";
4. bool
#
- Represents Boolean values,
true
andfalse
. - Examples:
bool isDartFun = true;
Collections#
1. List
#
- An ordered collection of values, similar to arrays.
- Examples:
List<int> numbers = [1, 2, 3];
2. Set
#
- An unordered collection of unique items.
- Examples:
Set<String> names = {'Alice', 'Bob'};
3. Map
#
- A collection of key-value pairs, akin to dictionaries in Python.
- Examples:
Map<String, int> phoneNumbers = {'John': 123456, 'Doe': 987654};
Special Data Types#
1. dynamic
#
- The variable can be set to anything, and type checks are deferred until runtime.
- Examples:
dynamic x = 'Hello'; x = 123;
2. var
#
- Automatically infers the data type based on the assigned value.
- Examples:
var y = 'Hello'; // y is a String
3. final
and const
#
final
variables can only be set once and initialized when accessed.const
variables are implicitly final but are a compile-time constant.- Examples:
final cityName = 'New York';
const double pi = 3.14159;
Null Safety#
- Dart supports null safety, meaning you have to explicitly declare a variable that can be null using the
?
after the type. - Examples:
int? mightBeNull;
mightBeNull = null;
Conclusion#
Understanding these data types and their proper usage is fundamental for effective programming in Dart. These types are the building blocks of any Dart application, influencing how data is stored, manipulated, and displayed.
Date Type#
You can declare a variable with a specific type:
void main() {
// Integer type
int age = 30;
// Double type
double height = 5.11;
// String type
String name = "Alice";
// Boolean type
bool isLogged = false;
// Dynamic type
dynamic anything = "Hello!";
anything = 42; // dynamic type can change
// List type
List<String> fruits = ['apple', 'banana', 'cherry'];
// Map type
Map<String, int> productQuantity = {
'apples': 2,
'bananas': 5,
'oranges': 3
};
// Printing the values
print('Name: $name, Age: $age, Height: $height, Logged in: $isLogged');
print('Dynamic type variable now contains: $anything');
print('Fruits: $fruits');
print('Product quantities: $productQuantity');
}