Dart Data Types
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →Dart is a statically typed language with a rich set of built-in data types. Understanding these types is crucial for efficient programming and type safety.
Basic Data Types
Numbers
Dart provides two number types:
int: For whole numbersdouble: For floating-point numbers
Example:
int age = 30;
double price = 19.99;
Strings
Text is represented using the String type. Dart supports both single and double quotes for string literals.
Example:
String name = 'John Doe';
String message = "Hello, World!";
Booleans
The bool type represents true or false values.
Example:
bool isActive = true;
bool hasPermission = false;
Collection Types
Lists
Dart uses List for ordered collections of objects. Lists are similar to arrays in other languages.
Example:
List<String> fruits = ['apple', 'banana', 'orange'];
Sets
A Set is an unordered collection of unique items.
Example:
Set<int> numbers = {1, 2, 3, 4, 5};
Maps
Dart's Map type represents key-value pairs.
Example:
Map<String, int> ages = {
'John': 30,
'Jane': 25,
'Bob': 40
};
Special Types
Dynamic
The dynamic type allows variables to hold values of any type.
Null Safety
Dart supports Null Safety, which helps prevent null reference errors. Use the ? operator to declare nullable types.
Example:
String? nullableName;
int nonNullableAge = 25;
Best Practices
- Use specific types when possible for better type safety and code clarity.
- Leverage Dart's type inference to reduce verbosity while maintaining type safety.
- Consider using Dart Generics for more flexible and reusable code.
- Be mindful of Type Promotion when working with nullable types.
Conclusion
Understanding Dart's data types is fundamental to writing efficient and error-free code. As you progress, explore more advanced topics like Dart Classes and Dart Interfaces to fully leverage Dart's type system.