Data Types in Dart
In Dart, data types define what kind of data a variable can hold. Think of data types as different containers - you wouldn't store water in a paper bag or books in a fishbowl! Similarly, Dart uses specific data types to store different kinds of information efficiently.
Built-in Data Types
Dart has several built-in data types that cover most programming needs:
Numbers
Dart provides two types for numbers:
- int - for integers (whole numbers)
- double - for floating-point numbers (decimals)
int age = 25;
int temperature = -10;
double price = 19.99;
double pi = 3.14159;
Strings
Strings represent text data and are enclosed in single or double quotes:
String name = 'Alice';
String message = "Hello, World!";
String multiline = '''
This is a
multi-line
string
''';
Booleans
Booleans represent true/false values:
bool isActive = true;
bool isComplete = false;
Lists
Lists are ordered collections of items (similar to arrays in other languages):
List<int> numbers = [1, 2, 3, 4, 5];
List<String> fruits = ['apple', 'banana', 'orange'];
var mixedList = [1, 'hello', true]; // Dynamic list
Maps
Maps store key-value pairs (like dictionaries):
Map<String, int> scores = {
'Alice': 95,
'Bob': 87,
'Charlie': 92
};
var person = {
'name': 'John',
'age': 30,
'city': 'New York'
};
Type Inference
Dart is smart! It can often figure out the data type automatically using the var keyword:
var name = 'Alice'; // Dart knows this is a String
var age = 25; // Dart knows this is an int
var price = 19.99; // Dart knows this is a double
var isActive = true; // Dart knows this is a bool
Dynamic Type
Sometimes you need flexibility. The dynamic type can hold any type of data:
dynamic flexible = 'Hello';
flexible = 42; // Now it's an int
flexible = true; // Now it's a bool
Type Safety
Dart is type-safe, meaning once a variable is assigned a type, it must stick to that type:
String name = 'Alice';
// name = 42; // This would cause an error!
Common Data Type Operations
Here are some useful operations you can perform:
// String operations
String greeting = 'Hello';
String fullGreeting = greeting + ' World!'; // Concatenation
int length = greeting.length; // Get length
// Number operations
int a = 10;
int b = 3;
double result = a / b; // Division always returns double
// List operations
List<String> colors = ['red', 'green', 'blue'];
colors.add('yellow'); // Add item
int count = colors.length; // Get count
String first = colors[0]; // Access by index
Understanding data types is fundamental to Dart programming. They help you write more reliable code and catch errors early. As you continue learning, you'll discover how these types work together to build amazing applications!