Future وAsync/Await
افهم فئة `Future` في Dart والكلمتين المفتاحيتين `async` و`await` لتنفيذ العمليات غير الحاجبة والتعامل مع النتائج المؤجلة
Future وAsync/Await درس مجاني في Flutter Mobile Development على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Flutter Mobile Development، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Flutter Mobile Development 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
What is Asynchronous Code?
In app development, we often need to perform tasks that take time, like fetching data from the internet or reading a file.
If these tasks block your app's main thread, your UI becomes unresponsive and freezes. This is a bad user experience!
Asynchronous programming allows your app to start a long-running task and continue doing other things (like updating the UI) while waiting for the task to finish.
The Problem with Blocking Code
Imagine a task that takes 3 seconds. If it runs on the main thread, your app will freeze for 3 seconds. Try running this example to see how it blocks:
void main() {
print("Starting a long task...");
// Simulate a long-running operation
var result = _performHeavyCalculation();
print("Task finished with result: $result");
print("End of program.");
}
String _performHeavyCalculation() {
// Simulate delay without async/await
var startTime = DateTime.now();
while (DateTime.now().difference(startTime).inSeconds < 3) {
// Busy-wait, blocking the thread
}
return "Calculated Data";
}Meet the Dart Future
Dart's Future class is your solution for non-blocking operations. A Future represents a potential value or error that will be available at some point in the future.
- It's like an IOU (I Owe You) for a value.
- When you call an asynchronous function, it immediately returns a
Futureobject. - The actual result will be delivered to the
Futurewhen the operation completes.
Think of it as ordering food; you get a receipt (the Future) immediately, but the food (the value) comes later.
Making a Simple Future
You can create a Future that completes after a delay using Future.delayed. It takes a duration and a function to execute when the delay is over.
Run this code to see how the "Data received!" message appears after a short wait, without blocking the "Program continues!" message.
void main() {
print("Program starts!");
Future.delayed(Duration(seconds: 2), () {
print("Data received after 2 seconds!");
});
print("Program continues immediately!");
print("End of main function.");
}Getting Values with .then()
To actually use the value a Future eventually provides, you attach a callback function using the .then() method.
The code inside .then() will only run once the Future successfully completes and delivers its value. This is how you react to a completed async task.
void main() {
print("Fetching user data...");
_fetchUserData().then((userData) {
print("User data fetched: $userData");
});
print("UI can update while data fetches.");
}
Future<String> _fetchUserData() {
return Future.delayed(Duration(seconds: 2), () => "Alice (ID: 123)");
}Handling Future Errors
Asynchronous operations can fail (e.g., network issues). To handle errors, you can chain .catchError() after .then(). This callback will execute if the Future completes with an error.
.catchError() receives the error object, allowing you to react gracefully to problems.
void main() {
print("Attempting to fetch data...");
_fetchFaultyData().then((data) {
print("Data received: $data");
}).catchError((error) {
print("Error caught: $error");
});
}
Future<String> _fetchFaultyData() {
return Future.delayed(Duration(seconds: 2), () {
throw Exception("Failed to connect to server!");
});
}Simplify with async and await
While .then() and .catchError() work, chaining many of them can become hard to read. Dart offers async and await keywords to make asynchronous code look and feel more like synchronous code.
async: Marks a function as asynchronous. Anasyncfunction always returns aFuture.await: Can only be used inside anasyncfunction. It pauses the execution of theasyncfunction until theFutureit's waiting on completes.
The rest of the program continues to run while an await is active.
Async/Await in Action
Let's rewrite our user data fetching example using async and await. Notice how much cleaner and more sequential the code looks!
The await keyword makes the code inside main appear to wait, but the main function itself is an async function, so it actually returns a Future and doesn't block the overall program.
void main() async { // main function is now async
print("Fetching user data with async/await...");
String userData = await _fetchUserData(); // Await the Future
print("User data fetched: $userData");
print("UI can update while data fetches.");
}
Future<String> _fetchUserData() {
return Future.delayed(Duration(seconds: 2), () => "Bob (ID: 456)");
}Try-Catch with Async/Await
With async and await, error handling becomes familiar! You can use standard try-catch blocks around await expressions to catch exceptions thrown by Futures.
This makes managing potential failures in asynchronous operations much more intuitive and readable.
void main() async {
print("Attempting to fetch data with try-catch...");
try {
String data = await _fetchFaultyData();
print("Data received: $data");
} catch (e) {
print("Error caught: $e");
}
print("Program continues after error handling.");
}
Future<String> _fetchFaultyData() {
return Future.delayed(Duration(seconds: 2), () {
throw Exception("Network connection lost!");
});
}Check Your Understanding
Consider the following Dart code snippet:
void main() async {
print("A");
await Future.delayed(Duration(seconds: 1), () => print("B"));
print("C");
}Futures & Async/Await Recap
You've mastered the basics of asynchronous programming in Dart!
Future: A placeholder for a value that will be available later..then()/.catchError(): Methods to handle aFuture's success or failure.async: Marks a function that performs asynchronous operations and returns aFuture.await: Pauses anasyncfunction until aFuturecompletes, making async code read like sync code.try-catch: Used withawaitfor robust error handling.
These tools are crucial for building responsive Flutter apps that interact with external resources. Next, we'll use these concepts to make HTTP requests!
الأسئلة الشائعة
هل درس «Future وAsync/Await» مجاني؟
نعم — نص درس «Future وAsync/Await» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Flutter Mobile Development، انتقل إلى CoddyKit PRO. تتضمن دورة Flutter Mobile Development 4 دروس في المجموع.
ماذا ستتعلم في «Future وAsync/Await»؟
افهم فئة `Future` في Dart والكلمتين المفتاحيتين `async` و`await` لتنفيذ العمليات غير الحاجبة والتعامل مع النتائج المؤجلة تتمرن على Flutter Mobile Development مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Flutter Mobile Development؟
لا تُشترط خبرة سابقة. Flutter Mobile Development على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «Future وAsync/Await»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Flutter Mobile Development هذا؟
نعم. كل درس في Flutter Mobile Development يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- Future وAsync/Await
- طلبات HTTP وJSON
- معالجة الأخطاء في العمليات غير المتزامنة
- Streams والبيانات التفاعلية