Dart Security Basics
In this lesson, you will learn the fundamentals of security in Dart applications and how to protect your code, data, and users from common vulnerabilities.
Security is not optional in real-world applications. Even small Dart programs can expose sensitive information if security is ignored.
Why Security Matters
Security protects:
- User data (emails, passwords, personal info)
- Application logic
- APIs and backend services
- System resources
A single security flaw can lead to data leaks, system abuse, or financial loss.
Common Security Risks in Dart Apps
- Hardcoded credentials
- Unvalidated user input
- Improper error handling
- Insecure API communication
- Exposing sensitive logs
Understanding these risks is the first step to preventing them.
Avoid Hardcoding Sensitive Data
Never hardcode passwords, tokens, or API keys directly in code.
// ❌ Insecure
String apiKey = "sk_live_ABC123SECRET";
Instead, use environment variables or secure storage.
// ✅ Secure approach (example)
String apiKey = Platform.environment['API_KEY'] ?? "";
Validate User Input
User input must always be validated before processing.
Example: validating an age value entered by a user.
int? age = int.tryParse(userInput);
if (age == null || age < 0 || age > 120) {
print("Invalid age input");
} else {
print("Age accepted: $age");
}
Never trust user input blindly.
Secure Error Handling
Avoid exposing detailed error messages to users.
// ❌ Too much detail
catch (e) {
print(e);
}
Instead, log safely and show generic messages.
// ✅ Safer approach
catch (e) {
print("Something went wrong");
}
Secure API Communication
Always use HTTPS when communicating with APIs.
Example of a secure HTTP request:
final url = Uri.parse("https://api.example.com/data");
Avoid sending sensitive data over plain HTTP.
Protect Sensitive Logs
Logging sensitive information can create security risks.
// ❌ Risky logging
print("User password: $password");
Instead, log only necessary and masked data.
// ✅ Safe logging
print("User login attempt");
Use Secure Packages
Always prefer well-maintained and trusted Dart packages.
- Check package popularity
- Review last update date
- Avoid unknown or abandoned libraries
Security of dependencies matters as much as your own code.
Data Validation Example
Validating an email address before saving it.
bool isValidEmail(String email) {
return email.contains("@") && email.contains(".");
}
print(isValidEmail("user@example.com")); // true
print(isValidEmail("userexample")); // false
Security Best Practices
- Never trust user input
- Avoid exposing internal logic
- Keep dependencies updated
- Use HTTPS always
- Log responsibly
📝 Practice Exercises
Exercise 1
Write a function that validates a phone number input.
Exercise 2
Identify insecure code that exposes sensitive information.
Exercise 3
Create a safe error-handling block for API calls.
What’s Next?
In the next lesson, you will learn about Dart Concurrency and how Dart handles multiple tasks efficiently.