Understanding data types is a fundamental step in learning any programming language. In Dart, data types define the kind of data a variable can hold, such as numbers, text, or logical values. Dart is a strongly typed language, but it also provides flexibility with type inference using var and dynamic typing using dynamic.
In this comprehensive guide, we’ll cover:
- Introduction to Dart data types
- Numeric types:
intanddouble - Text type:
String - Boolean type:
bool - Type inference with
var - Dynamic typing with
dynamic - Null safety and nullable types
- Type conversions
- Best practices for using Dart data types
- Real-world examples and use cases
Introduction to Dart Data Types
A data type in Dart specifies the kind of data a variable can store. Dart variables are declared using a type, which helps the compiler detect errors and optimize performance.
int age = 25;
double price = 99.99;
String name = "John Doe";
bool isLoggedIn = true;
Key Points
- Dart is statically typed, meaning types are checked at compile time.
- Dart supports type inference, allowing you to omit the type in certain cases.
- Dart has null safety, preventing null reference errors by distinguishing nullable and non-nullable types.
Numeric Types in Dart
Dart supports two primary numeric types: int and double.
1. int – Integer Numbers
- Represents whole numbers without decimals.
- Can be positive or negative.
- Examples:
int age = 30;
int year = 2025;
int temperature = -5;
Operations with int
int a = 10;
int b = 3;
print(a + b); // 13
print(a - b); // 7
print(a * b); // 30
print(a ~/ b); // 3 (integer division)
print(a % b); // 1 (modulo)
2. double – Floating-Point Numbers
- Represents numbers with decimal points.
- Examples:
double price = 19.99;
double pi = 3.14159;
double temperature = -5.5;
Operations with double
double a = 5.5;
double b = 2.0;
print(a + b); // 7.5
print(a - b); // 3.5
print(a * b); // 11.0
print(a / b); // 2.75
Text Type in Dart
1. String – Text
- Used to store textual data.
- Can use single quotes
', double quotes", or triple quotes'''/"""for multi-line strings.
String name = "John";
String greeting = 'Hello, Dart!';
String multiLine = '''
This is
a multi-line
string.
''';
String Interpolation
int age = 25;
String message = "My age is $age";
print(message); // My age is 25
Boolean Type in Dart
1. bool – True or False
- Represents logical values.
- Only two values:
trueorfalse.
bool isLoggedIn = true;
bool hasAccess = false;
Conditional Example
bool isRaining = true;
if (isRaining) {
print("Take an umbrella!");
} else {
print("Enjoy the sun!");
}
Type Inference with var
Dart allows type inference, where the compiler infers the variable type from the assigned value.
var name = "Alice"; // inferred as String
var age = 30; // inferred as int
var price = 99.99; // inferred as double
Note: Once a type is inferred, it cannot change.
var age = 25;
age = "twenty-five"; // ❌ Error: type mismatch
Dynamic Typing with dynamic
The dynamic keyword allows variables to change type at runtime.
dynamic data = "Hello";
print(data); // Hello
data = 100;
print(data); // 100
dynamicdisables compile-time type checking, so use it cautiously.
Null Safety and Nullable Types
Dart introduced null safety to avoid null reference errors.
int? age = null; // nullable int
String? name; // can be null
- Non-nullable types (default) cannot be null:
int age = 25;
// age = null; ❌ Error
- Nullable types are declared with
?.
int? score = null;
score = 100; // valid
Type Conversions
Dart allows conversion between compatible types.
Examples
String strNumber = "42";
int number = int.parse(strNumber);
double decimal = double.parse("3.14");
int num = 10;
String numStr = num.toString();
Always handle exceptions when parsing strings.
Best Practices for Using Dart Data Types
- Prefer non-nullable types for safety.
- Use
varfor simplicity, but know the inferred type. - Use
dynamicsparingly – it bypasses compile-time checks. - Use
finalorconstfor immutable data. - Leverage type conversions to avoid runtime errors.
- Use descriptive variable names to clarify type and purpose.
Real-World Examples
Example 1: Simple User Profile
String username = "Alice";
int age = 30;
double height = 5.6;
bool isPremium = true;
print("User: $username, Age: $age, Height: $height, Premium: $isPremium");
Example 2: Dynamic Data
dynamic data = 100;
print(data); // 100
data = "Hello Dart!";
print(data); // Hello Dart!
Example 3: Nullable Score
int? score;
if (score == null) {
print("Score not available");
} else {
print("Score: $score");
}
Leave a Reply