Dart Assert
Debug and validate your Dart code
✅ What is Assert?
Assert statements help you debug code by checking if conditions are true during development. They throw errors when conditions fail, helping you catch bugs early in development.
// Basic assert example
int age = 25;
assert(age >= 0, 'Age cannot be negative');
print('Age is valid: $age');
Assert Features
Debug Tool
Only works in debug mode
assert(condition);
// Ignored in production
Custom Messages
Add helpful error messages
assert(x > 0,
'x must be positive');
Fast Validation
Quick condition checking
assert(list.isNotEmpty);
assert(name != null);
Safety Check
Prevent invalid states
assert(index >= 0 &&
index < list.length);
🔹 Basic Assert Usage
Simple assert statements for common validations:
void main() {
int score = 85;
String name = 'John';
List numbers = [1, 2, 3];
// Basic assertions
assert(score >= 0 && score <= 100);
assert(name.isNotEmpty);
assert(numbers.length > 0);
print('All validations passed!');
}
Output (Debug Mode):
All validations passed!
🔹 Assert with Messages
Add descriptive messages to make debugging easier:
void calculateArea(double width, double height) {
assert(width > 0, 'Width must be positive, got: $width');
assert(height > 0, 'Height must be positive, got: $height');
double area = width * height;
print('Area: $area');
}
void main() {
calculateArea(5.0, 3.0); // Works fine
// calculateArea(-2.0, 3.0); // Would throw assertion error
}
Output:
Area: 15.0
🔹 Common Assert Patterns
Typical ways to use assert in your code:
🔸 Function Parameters
void divide(int a, int b) {
assert(b != 0, 'Cannot divide by zero');
print('Result: ${a / b}');
}
void setAge(int age) {
assert(age >= 0 && age <= 150, 'Invalid age: $age');
print('Age set to: $age');
}
🔸 List Operations
void getItem(List items, int index) {
assert(items.isNotEmpty, 'List cannot be empty');
assert(index >= 0 && index < items.length,
'Index $index out of bounds');
print('Item: ${items[index]}');
}
🔹 Assert vs Exceptions
Understanding when to use assert vs throwing exceptions:
Use Assert for:
- Development debugging: Catch logic errors early
- Internal validation: Check your own code assumptions
- Performance: No cost in production builds
Use Exceptions for:
- User input validation: Handle invalid user data
- Runtime errors: Network failures, file not found
- Production code: Errors that can occur in release
void processUserInput(String input) {
// Use exception for user input
if (input.isEmpty) {
throw ArgumentError('Input cannot be empty');
}
List parts = input.split(',');
// Use assert for internal logic
assert(parts.isNotEmpty, 'Split should never return empty list');
print('Processing: $parts');
}
🔹 Enabling/Disabling Asserts
Control when asserts are active:
Assert Modes:
- Debug Mode: Asserts are enabled (default in development)
- Release Mode: Asserts are ignored (production builds)
- Custom: Use --enable-asserts flag to control
void main() {
// This will only run in debug mode
assert(() {
print('Debug mode is active!');
return true;
}());
print('Program continues...');
}