Dart Real-World Scenarios
In this lesson, you will learn how Dart is used in real-world applications. Instead of focusing only on syntax, we will solve practical problems that developers face every day.
These examples simulate production-style workflows using asynchronous operations, data handling, error control, and performance awareness.
Scenario 1: User Registration System
A common real-world use case is registering users by validating input, saving data, and returning a response.
Future saveUser(String name, int age) async {
await Future.delayed(Duration(seconds: 1));
return age >= 18;
}
void main() async {
bool isSaved = await saveUser("Alex", 24);
print(isSaved ? "User Registered" : "Registration Failed");
}
This pattern is commonly used in forms, APIs, and mobile apps.
Scenario 2: Fetching Data from an API
Applications frequently retrieve data from remote servers. Below is a simulated API call returning product prices.
Future> fetchPrices() async {
await Future.delayed(Duration(seconds: 2));
return [1200, 899, 450, 300];
}
void main() async {
var prices = await fetchPrices();
int total = prices.reduce((a, b) => a + b);
print("Total Price: $total");
}
This pattern is widely used in e-commerce and dashboards.
Scenario 3: File Processing Workflow
Reading files, processing content, and saving output is a common backend task.
Future processFile() async {
await Future.delayed(Duration(seconds: 1));
return 350; // number of records processed
}
void main() async {
int count = await processFile();
print("Processed $count records");
}
Used in ETL jobs, reporting systems, and batch operations.
Scenario 4: Background Notifications
Some operations should run in the background without blocking users.
void sendNotification() {
Future(() {
print("Notification sent");
});
}
void main() {
print("User Action Completed");
sendNotification();
}
This is common in logging, alerts, and analytics.
Scenario 5: Error Handling in Production
Errors must be handled gracefully to avoid crashes.
Future calculateDiscount(double price) async {
if (price <= 0) {
throw Exception("Invalid price");
}
return price * 0.1;
}
void main() async {
try {
double discount = await calculateDiscount(500);
print("Discount: $discount");
} catch (e) {
print("Error: $e");
}
}
This pattern improves stability and user trust.
Scenario 6: Real-Time Data Updates
Live data streams are essential in chat apps, dashboards, and sensors.
Stream liveOrders() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i * 10;
}
}
void main() async {
await for (var orders in liveOrders()) {
print("Orders processed: $orders");
}
}
Streams allow continuous data handling efficiently.
Scenario 7: Performance Optimization Example
Parallel execution reduces waiting time in real systems.
Future taskA() async {
await Future.delayed(Duration(seconds: 2));
return 40;
}
Future taskB() async {
await Future.delayed(Duration(seconds: 2));
return 60;
}
void main() async {
var results = await Future.wait([taskA(), taskB()]);
print("Total: ${results[0] + results[1]}");
}
Parallelism improves scalability and responsiveness.
Where Dart Is Used in Real Life
- Mobile apps (Flutter)
- CLI tools
- Backend services
- Data processing pipelines
- Automation scripts
📝 Practice Exercises
Exercise 1
Simulate an API call that returns user scores and calculate the average.
Exercise 2
Create a background logging task using Futures.
Exercise 3
Build a stream that emits temperature values every second.
What’s Next?
In the next lesson, you will integrate Dart with databases, applying these real-world patterns to persistent data storage.