FlutterFlutter · Chapterبەش 5 · Lectureوانە 5.5
Futures, async and await in DartFuture، async و await لە Dartـدا
Dart's tools for waiting without freezing: the Future type, async and await, the event loop behind them, the course paper's file example made runnable and corrected, then(), errors, Future.wait, Streams, isolates for heavy work, and a first look at FutureBuilder and StreamBuilder.
ئامرازەکانی بۆ چاوەڕوانی بەبێ گیرخواردن: جۆری Future، async و await، ئەو لە پشتیانەوەیە، نموونەی فایلەکەی نووسینی وانەکە بە جێبەجێکراوی و چاککراوی، then()، ، Future.wait، ، بۆ کاری قورس و یەکەم سەیرکردنی FutureBuilder و StreamBuilder.
What you will learnچی فێر دەبیت
- Explain what a Future is and its states (uncompleted, completed with a value or an error).
- Write async functions and use
awaitcorrectly, and predict the order of output of async code. - Describe the event loop and why
awaitpauses only its own function. - Handle errors with try/catch, wait for several Futures with
Future.wait, and read a Stream. - Show a Future in Flutter with FutureBuilder, created once in initState.
- ڕوونی بکەیتەوە چییە و دۆخەکانی چین (تەواونەبوو، تەواوبوو بە نرخێک یان ).
- بنووسیت و
awaitبە دروستی بەکار بهێنیت و ڕیزبەندیی کۆدی پێشبینی بکەیت. - وەسف بکەیت و بۆچی
awaitتەنها خۆی ڕادەگرێت. - بە try/catch بەڕێوە ببەیت، بە
Future.waitچاوەڕێی چەند بکەیت و بخوێنیتەوە. - لە Flutterـدا بە
FutureBuilderپیشان بدەیت، کە یەک جار لەinitStateـدا دروست کرابێت.
From waiting to Dart codeلە چاوەڕوانییەوە بۆ کۆدی Dart
In Synchronous and Asynchronous Work you learned the idea: an app must not freeze while it waits for a file, a database or the network. This lesson shows how Dart does it, with real code that runs.
لە کاری هاوکات و ناهاوکات بیرۆکەکەت فێر بوویت: نابێت لە کاتی چاوەڕوانیی ، یان گیر بخوات. ئەم وانەیە پیشان دەدات چۆن ئەمە دەکات، بە کۆدی ڕاستەقینە کە جێبەجێ دەبێت.
The course paper on this topic is called Difference Between Future and Regular Methods in Flutter. Its Kurdish half names the two kinds a regular function (which gives its result at once) and a future function (whose result comes later). By the end of this lesson you will be able to explain that difference exactly, with Dart's three tools: the Future type and the keywords async and await.
ناونیشانی نووسینی وانەکە لەسەر ئەم بابەتە ئەمەیە: جیاوازیی نێوان ئاسایی و داهاتوویی لە Flutterـدا. ئەو دوو جۆرە ناودەبات: « ئاسایی» (کە ئەنجامەکەی یەکسەر دەدات) و « داهاتوویی» (کە ئەنجامەکەی دواتر دێت). لە کۆتایی ئەم وانەیەدا دەتوانیت ئەو جیاوازییە بە وردی ڕوون بکەیتەوە، بە سێ ئامرازەکەی : جۆری Future و async و await.
Future: a value that arrives laterFuture: نرخێک کە دواتر دێت
An object that stands for a value that will be ready later, after slow work such as a network request, a file operation or a database query. It is first uncompleted, then completes with a value or with an error. JavaScript calls the same idea a Promise.
کە جێگەی نرخێک دەگرێتەوە کە دواتر ئامادە دەبێت، دوای کارێکی هێواش وەک بۆ ڕایەڵە، کارێک لەسەر فایل یان بنکەدراوە. سەرەتا تەواونەبووە، پاشان بە نرخێک یان بە هەڵەیەک تەواو دەبێت. JavaScript هەمان بیرۆکە بە Promise ناو دەبات.
A Future represents a value that will be available in the future: in the next second or later. It is used for tasks that need time: sending data to the internet and getting data from it, file operations and database queries.
Future نوێنەرایەتیی نرخێک دەکات کە لە داهاتوودا بەردەست دەبێت: لە چرکەی داهاتوودا یان دواتر. بۆ ئەو ئەرکانە بەکار دێت کە کاتیان پێویستە: ناردنی دراوە بۆ و وەرگرتنی دراوە لێیەوە، کارەکانی سەر و .
A Future is first uncompleted: the work is still going on. Later it becomes completed, in one of two ways: with a value (the work succeeded) or with an error (it failed). Future<int> means: when it completes with a value, the value is an int. A function that gives nothing back returns Future<void>.
سەرەتا تەواونەبووە: کارەکە هێشتا بەردەوامە. دواتر تەواو دەبێت، بە یەکێک لە دوو ڕێگا: بە نرخێک (کارەکە سەرکەوتوو بوو) یان بە (شکستی هێنا). Future<int> واتە: کاتێک بە نرخێک تەواو بوو، نرخەکە intـە. کە هیچ ناگەڕێنێتەوە Future<void> دەگەڕێنێتەوە.
Two short Dart chapters from freeCodeCamp: adding methods to a class with an extension, and what a Future is.
دوو بەشی کورتی لە freeCodeCampـەوە: زیادکردنی بۆ بە extension، هەروەها (Future) چییە.
Plays 4:30:02-4:33:57: Futures and Future.delayed, just before async/await.
لە 4:30:02 تا 4:33:57 پەخش دەبێت: و Future.delayed، ڕێک پێش .
Future: a value that arrives laterFuture: نرخێک کە دواتر دێت
A class, not a keyword: the receiptکلاسێک، نەک وشەی کلیلەیی: پسوولەکە
At a busy kebab shop in the bazaar you pay and get a numbered receipt. The receipt is not food, but it promises food later. While you wait you can sit, drink tea and talk. When your number is called you swap the receipt for your kebab (a value), or the cook says the meat is finished (an error).
لە دوکانێکی قەرەباڵغی کەباب لە بازاڕ پارە دەدەیت و پسوولەیەکی ژمارەدار وەردەگریت. پسوولەکە خواردن نییە، بەڵام بەڵێنی خواردن دەدات بۆ دواتر. لە کاتی چاوەڕوانیدا دەتوانیت دابنیشیت، چا بخۆیتەوە و قسە بکەیت. کاتێک ژمارەکەت بانگ کرا پسوولەکە بە کەبابەکەت دەگۆڕیتەوە (نرخێک)، یان کەبابچییەکە دەڵێت گۆشت نەماوە ().
Where the analogy stops workingسنووری ئەم نموونەیە
A receipt can be lost or kept forever; a Future always completes once, and Dart tells your code exactly when.
پسوولە دەکرێت ون ببێت یان بۆ هەمیشە بمێنێتەوە؛ هەمیشە یەک جار تەواو دەبێت و بە وردی بە کۆدەکەت دەڵێت کەی.
async and awaitasync و await
The two Dart keywords for asynchronous code: async marks a function as asynchronous, and await, allowed only inside it, pauses that function until a completes, while the keeps the rest of the app running.
دوو وشە کلیلەییەکەی Dartـن بۆ کۆدی ناهاوکات: async کردارێک وەک ناهاوکات نیشانە دەکات و await، کە تەنها لە ناویدا ڕێگەپێدراوە، ئەو کردارە ڕادەگرێت تا تەواو دەبێت، لە کاتێکدا بەشەکانی تری ئەپەکە بەردەوام کارا دەهێڵێتەوە.
- The word
asyncmarks a function as asynchronous. Every async function automatically returns a Future:Future<int>,Future<String>orFuture<void>. - The word
awaitcan be used only inside an async function. The functions you call inside an async function do not all needawait, only the ones whose result you must wait for. - A call marked with
awaitstops this function from going to its next line until the Future has completed. Only this async function waits; meanwhile the rest of the program keeps running. - To get the value out of a Future you use
await(orthen, later in this lesson).
- وشەی
asyncوەک نیشانە دەکات. هەموو بە شێوەی خۆکار دەگەڕێنێتەوە:Future<int>،Future<String>یانFuture<void>. - وشەی
awaitتەنها لەنێو بەکار دێت. ئەو لەنێو بانگیان دەکەیت هەموویان پێویستیان بەawaitنییە، تەنها ئەوانەی کە دەبێت چاوەڕێی ئەنجامەکەیان بکەیت. - بانگکردنێک کە بە
awaitنیشانە کرابێت ئەم لە چوون بۆ دێڕی دواتری ڕادەگرێت تا تەواو دەبێت. تەنها ئەم چاوەڕێ دەکات؛ لەو کاتەدا بەشەکانی تری بەردەوام کار دەکەن. - بۆ دەرهێنانی نرخەکە لە
awaitبەکار دەهێنیت (یانthen، دواتر لەم وانەیەدا).
The paper's own example adds two numbers in an async function:
نموونەکەی خودی نووسینەکە دوو ژمارە لە کۆ دەکاتەوە:
Future<int> addNumbersAsync(int a, int b) async {
return a + b; // Same behavior, but explicit
}
void main() async {
int result = await addNumbersAsync(5, 10);
print('Result: $result');
}Result: 15
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
asyncmakes the return typeFuture<int>, although the body just returns anint.asyncجۆری دەکات بەFuture<int>، هەرچەندە جەستەکە تەنهاintـێک دەگەڕێنێتەوە.- Lineدێڕی 6
awaitunwraps the Future and gives the plainint15.awaitدەکاتەوە وintـی سادەی 15 دەدات.
The comment Same behavior, but explicit compares this function with a regular version that the paper does not show. Here are both side by side, and what you get before await:
لێدوانی Same behavior, but explicit ئەم بەراورد دەکات بە وەشانێکی ئاسایی کە نووسینەکە پیشانی نادات. ئەمە هەردووکیانن لە تەنیشت یەکەوە و ئەوەی پێش await وەری دەگریت:
// A regular function: the result comes back at once.
int addNumbers(int a, int b) {
return a + b;
}
// An async function: the result comes back inside a Future.
Future<int> addNumbersAsync(int a, int b) async {
return a + b;
}
Future<void> main() async {
int now = addNumbers(5, 10);
Future<int> box = addNumbersAsync(5, 10);
int later = await box;
print('Regular: $now');
print('Async, before await: $box');
print('Async, after await: $later');
}Regular: 15 Async, before await: Instance of 'Future<int>' Async, after await: 15
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 12
The regular function returns 15 at once.
ئاسایی یەکسەر 15 دەگەڕێنێتەوە.
- Lineدێڕی 13
The async function returns a Future, not 15.
دەگەڕێنێتەوە، نەک 15.
- Lineدێڕی 14
awaitwaits for the Future and takes the 15 out of it.awaitچاوەڕێی دەکات و 15ـەکەی لێ دەردەهێنێت.
async and awaitasync و await
An async function starts at onceکرداری ناهاوکات یەکسەر دەست پێ دەکات
Calling an async function does not put the whole function off. Its code runs straight away, like normal code, until the first await. There it pauses, returns its Future to the caller, and the caller continues.
بانگکردنی هەموو دوا ناخات. کۆدەکەی یەکسەر جێبەجێ دەبێت، وەک کۆدی ئاسایی، تا یەکەم await. لەوێ ڕادەوەستێت، دەداتەوە بە بانگکەر و بانگکەر بەردەوام دەبێت.
Future<void> makeTea() async {
print('2. Kettle on'); // runs at once, like normal code
await Future.delayed(const Duration(seconds: 2));
print('4. Tea is ready'); // runs later, when the timer event comes
}
void main() {
print('1. Order taken');
makeTea(); // runs until its first await, then main continues
print('3. Taking the next order');
}1. Order taken 2. Kettle on 3. Taking the next order 4. Tea is ready
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Runs at once, as part of the call on line 9.
یەکسەر جێبەجێ دەبێت، وەک بەشێک لە بانگکردنەکەی دێڕی ٩.
- Lineدێڕی 3
makeTeapauses here; control goes back tomain.makeTeaلێرەدا ڕادەوەستێت؛ کۆنترۆڵ دەگەڕێتەوە بۆmain.- Lineدێڕی 10
maindid not wait (noawait), so it prints line 3 now.mainچاوەڕێی نەکرد (awaitنییە)، بۆیە ئێستا دێڕی ٣ چاپ دەکات.- Lineدێڕی 4
Two seconds later the timer event arrives and
makeTeafinishes.دوو چرکە دواتر ڕووداوی کاتژمێرەکە دەگات و
makeTeaتەواو دەبێت.
This is the tea-house waiter of the shared lesson in code: the kettle is put on (2), the waiter takes the next order (3), and the tea is served when it is ready (4).
ئەمە چایچییەکەی وانە هاوبەشەکەیە بە کۆد: کترییەکە دادەنرێت (٢)، چایچییەکە داواکاریی دواتر وەردەگرێت (٣) و چاییەکە کاتێک ئامادە بوو پێشکەش دەکرێت (٤).
The paper's file example, made runnableنموونەی فایلەکەی نووسینەکە، بە شێوەیەکی جێبەجێکراو
The paper shows the same task twice, first without and then with async and await:
نووسینەکە هەمان ئەرک دوو جار پیشان دەدات، سەرەتا بەبێ و پاشان بە async و awaitـەوە:
async و awaitDARTvoid main() {
print("Start");
data = readFile("file.txt"); // This takes time
processData(data);
print("End");
}async و awaitـەوەDARTvoid main() async {
print("Start");
data = await readFile("file.txt"); // This takes time but doesn't block
processData(data);
print("End");
}Error: Method not found: 'readFile'. Error: Setter not found: 'data'. Error: Undefined name 'data'. Error: Method not found: 'processData'.
The paper's file example, made runnableنموونەی فایلەکەی نووسینەکە، بە شێوەیەکی جێبەجێکراو
The runnable version: who really waits?وەشانە جێبەجێکراوەکە: کێ بەڕاستی چاوەڕێ دەکات؟
Future<String> readFile(String name) async {
await Future.delayed(const Duration(seconds: 3)); // pretend the disk is slow
return 'contents of $name';
}
void processData(String data) => print('Processing: $data');
Future<void> main() async {
print('Start');
Future.delayed(const Duration(seconds: 1), () => print('(a timer fired while main was waiting)'));
final data = await readFile('file.txt'); // main pauses here
processData(data);
print('End');
}Start (a timer fired while main was waiting) Processing: contents of file.txt End
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1-4
readFilereturns aFuture<String>that completes after 3 seconds.readFileFuture<String>ـێک دەگەڕێنێتەوە کە دوای ٣ چرکە تەواو دەبێت.- Lineدێڕی 10
A timer: its callback is an event that will be due after 1 second.
کاتژمێرێک: کە دوای ١ چرکە کاتی دێت.
- Lineدێڕی 11
mainpauses here for 3 seconds, but the event loop is free.mainلێرەدا ٣ چرکە ڕادەوەستێت، بەڵام ئازادە.- Lineدێڕی 12-13
Only after the Future completes does
maincontinue: Processing, then End.تەنها دوای تەواوبوونی
mainبەردەوام دەبێت: Processing، پاشان End.
The paper's file example, made runnableنموونەی فایلەکەی نووسینەکە، بە شێوەیەکی جێبەجێکراو
What real blocking looks likeڕێگریی ڕاستەقینە چۆنە
The paper's first example is meant to show synchronous reading, where the whole program stops. Dart can do that too: sleep() from dart:io blocks everything. Here is the same program with a blocking read and the same 1-second timer:
یەکەم نموونەی نووسینەکە بۆ پیشاندانی خوێندنەوەی ، کە تێیدا هەموو دەوەستێت. دەتوانێت ئەوەش بکات: sleep()ـی dart:io هەموو شت ڕادەگرێت. ئەمە هەمان بە خوێندنەوەیەکی ڕێگر و هەمان کاتژمێری ١ چرکەیی:
import 'dart:io';
String readFileBlocking(String name) {
sleep(const Duration(seconds: 3)); // blocks: nothing else can run
return 'contents of $name';
}
void processData(String data) => print('Processing: $data');
void main() {
print('Start');
Future.delayed(const Duration(seconds: 1), () => print('(the timer could only fire now)'));
final data = readFileBlocking('file.txt');
processData(data);
print('End');
}Start Processing: contents of file.txt End (the timer could only fire now)
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
sleepfreezes the isolate for 3 seconds: no events, no timers, no frames.sleepبۆ ٣ چرکە ڕادەگرێت: نە ، نە کاتژمێر، نە وێنە.- Lineدێڕی 12
The timer is due after 1 s, but its event cannot run while
mainis still busy.کاتژمێرەکە دوای ١ چرکە کاتی دێت، بەڵام ڕووداوەکەی ناتوانێت جێبەجێ ببێت لە کاتێکدا
mainهێشتا سەرقاڵە.
| Questionپرسیار | Blocking (sleep)ڕێگر (sleep) | Asynchronous (await) (await) |
|---|---|---|
| Order of the 4 linesڕیزبەندیی ٤ دێڕەکە | Start, Processing, End, timerStart، Processing، End، کاتژمێر | Start, timer, Processing, EndStart، کاتژمێر، Processing، End |
| Total timeکۆی کات | about 3 sنزیکەی ٣ چرکە | about 3 sنزیکەی ٣ چرکە |
| Can the timer, taps and screen frames run during the 3 s?ئایا کاتژمێر، دەستلێدان و نوێکردنەوەی شاشە لە ماوەی ٣ چرکەکەدا کار دەکەن؟ | No: the app is frozenنەخێر: گیری خواردووە | Yes: the app stays responsiveبەڵێ: دەمێنێتەوە |
Notice that the total time is the same. Asynchronous code does not make the file faster; it makes the app usable while it waits. Never use sleep in a Flutter app.
سەرنج بدە کۆی کاتەکە هەمان شتە. کۆدی خێراتر ناکات؛ وا دەکات لە کاتی چاوەڕوانیدا بتوانیت بەکار بهێنیت. هەرگیز sleep لە Flutterـدا بەکار مەهێنە.
The event loop: one thing at a timeخولی ڕووداوەکان: یەک کار لە یەک کاتدا
The part of a program's that keeps taking the next from a queue (a tap, a timer, data that has arrived) and runs its code, one at a time. Asynchronous code works because a waiting function leaves the loop free for other events.
ئەو بەشەی سیستەمی کارپێکردنی بەرنامەیە () کە بەردەوام دواتر لە ڕیزێکەوە وەردەگرێت (دەستلێدانێک، کاتژمێرێک، دراوەیەک کە گەیشتووە) و کۆدەکەی کارا دەکات، یەک لە دوای یەک. کۆدی ناهاوکات کار دەکات چونکە کارێکی چاوەڕوان خولەکە بۆ ڕووداوەکانی تر بەتاڵ دەهێڵێتەوە.
How can main wait while the timer runs, if Dart does only one thing at a time? All Dart code runs inside an isolate. An isolate has one event queue and one event loop. Taps, timers, screen repaints and "your file is ready" messages are all events that wait in the queue. The loop takes the next event, runs its code to the end, then takes the next one.
چۆن main دەتوانێت چاوەڕێ بکات لە کاتێکدا کاتژمێرەکە کار دەکات، ئەگەر لە یەک کاتدا تەنها یەک کار بکات؟ هەموو کۆدێکی لەنێو جێبەجێ دەبێت. هەر یەک و یەک هەیە. دەستلێدان، کاتژمێر، دووبارە کێشانەوەی شاشە و پەیامی « ئامادەیە» هەموویان کە لە چاوەڕێ دەکەن. ڕووداوی دواتر وەردەگرێت، کۆدەکەی تا کۆتایی جێبەجێ دەکات و پاشان ڕووداوی دواتر وەردەگرێت.
The event loop: one thing at a timeخولی ڕووداوەکان: یەک کار لە یەک کاتدا
await gives the loop backawait خولی ڕووداوەکان ئازاد دەکات
await is the trick: when a function reaches await, it parks itself and gives the loop back. The loop serves other events. When the Future completes, an event to resume that function joins the queue, and the function continues from the line after await. Watch the paper's example run:
await نهێنییەکەیە: کاتێک دەگاتە await، خۆی ڕادەگرێت و ئازاد دەکات. خزمەتی ڕووداوەکانی تر دەکات. کاتێک تەواو دەبێت، ڕووداوێک بۆ درێژەدانی ئەو دەچێتە و لە دێڕی دوای awaitـەوە بەردەوام دەبێت. سەیری جێبەجێبوونی نموونەکەی نووسینەکە بکە:


The most common mistake: forgetting awaitباوترین هەڵە: لەبیرکردنی await
If you call an async function without await, you get the Future itself, the receipt, not the value:
ئەگەر بەبێ await بانگ بکەیت، خودی وەردەگریت، پسوولەکە، نەک نرخەکە:
Future<String> readFile(String name) async {
await Future.delayed(const Duration(seconds: 1));
return 'contents of $name';
}
void main() {
print('Start');
var data = readFile('file.txt'); // no await: data is a Future, not the text
print(data);
print('End');
}Start Instance of 'Future<String>' End
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 8
No
await:datais aFuture<String>, soprintshows the object, not the text.awaitنییە:dataFuture<String>ـێکە، بۆیەprintپیشان دەدات، نەک دەقەکە.
await و mainـی asyncDARTFuture<String> readFile(String name) async {
await Future.delayed(const Duration(seconds: 1));
return 'contents of $name';
}
Future<void> main() async {
print('Start');
var data = await readFile('file.txt'); // await: data is the String
print(data);
print('End');
}Start contents of file.txt End
The other way: then()ڕێگای تر: then()
Before async/await existed, Dart code reacted to Futures with callbacks. You will still see this style. then runs a callback with the value, catchError runs one for an error, and whenComplete runs at the end in both cases:
پێش ئەوەی async/await هەبێت، کۆدی بە وەڵامی دەدایەوە. هێشتا ئەم شێوازە دەبینیت. then بە نرخەکەوە جێبەجێ دەکات، catchError یەکێک بۆ و whenComplete لە کۆتاییدا لە هەردوو حاڵەتدا جێبەجێ دەبێت:
Future<String> fetchWeather(String city) {
return Future.delayed(const Duration(seconds: 1), () => 'Sunny in $city');
}
void main() {
print('Asking for the weather...');
fetchWeather('Erbil')
.then((report) => print(report))
.catchError((error) => print('Error: $error'))
.whenComplete(() => print('Done.'));
print('main has reached its last line');
}Asking for the weather... main has reached its last line Sunny in Erbil Done.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7-10
Three callbacks are registered; none of them runs yet.
سێ تۆمار دەکرێن؛ هیچیان هێشتا جێبەجێ نابن.
- Lineدێڕی 11
maindoes not wait, so its last line is printed first.mainچاوەڕێ ناکات، بۆیە دوایین دێڕەکەی سەرەتا چاپ دەکرێت.
The same with await reads from top to bottom, like normal code. That is why most modern Dart code prefers async/await, and uses then only for short one-liners.
هەمان شت بە await لە سەرەوە بۆ خوارەوە دەخوێنرێتەوە، وەک کۆدی ئاسایی. لەبەر ئەوە زۆربەی کۆدی نوێی async/await پێ باشترە و then تەنها بۆ کۆدی کورتی یەک دێڕی بەکار دەهێنێت.
awaitDARTFuture<String> fetchWeather(String city) {
return Future.delayed(const Duration(seconds: 1), () => 'Sunny in $city');
}
Future<void> main() async {
print('Asking for the weather...');
try {
final report = await fetchWeather('Erbil');
print(report);
} catch (error) {
print('Error: $error');
} finally {
print('Done.');
}
}Asking for the weather... Sunny in Erbil Done.
Errors: try, catch and finallyهەڵەکان: try، catch و finally
A Future can complete with an error: the network is down, the file is missing. With await, that error is thrown at the await line, so you catch it with the same try/catch you use in normal code. finally runs in both cases.
دەتوانێت بە تەواو ببێت: نییە، ون بووە. بە await، ئەو لە دێڕی await فڕێ دەدرێت، بۆیە بە هەمان try/catch دەیگریت کە لە کۆدی ئاساییدا بەکاری دەهێنیت. finally لە هەردوو حاڵەتدا جێبەجێ دەبێت.
Future<int> fetchPrice(String item) async {
await Future.delayed(const Duration(milliseconds: 500));
if (item == 'gold') {
throw Exception('price service is offline');
}
return 1500;
}
Future<void> main() async {
for (final item in ['tea', 'gold']) {
try {
final price = await fetchPrice(item);
print('$item: $price IQD');
} catch (e) {
print('$item: could not load ($e)');
} finally {
print('$item: finished');
}
}
}tea: 1500 IQD tea: finished gold: could not load (Exception: price service is offline) gold: finished
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
throwinside an async function completes its Future with an error.throwلەنێو بە تەواو دەکات.- Lineدێڕی 12
The error appears here, at the
await, and jumps tocatch.لێرە، لە
awaitـدا دەردەکەوێت و باز دەدات بۆcatch.- Lineدێڕی 16-18
finallyruns after success and after failure.finallyدوای سەرکەوتن و دوای شکستیش جێبەجێ دەبێت.
If nobody catches the error, the program crashes with an unhandled exception (the path is shortened here):
ئەگەر کەس نەگرێت، بە مامەڵەنەکراو دەکەوێت (ڕێڕەوەکە لێرەدا کورت کراوەتەوە):
Future<int> fetchPrice() async {
await Future.delayed(const Duration(milliseconds: 500));
throw Exception('price service is offline');
}
Future<void> main() async {
final price = await fetchPrice(); // no try/catch
print('Price: $price');
}Unhandled exception: Exception: price service is offline #0 fetchPrice (file:///…/uncaught.dart:3:3) <asynchronous suspension> #1 main (file:///…/uncaught.dart:7:17) <asynchronous suspension>
Waiting for several Futures: Future.waitچاوەڕوانیی چەند نرخێکی داهاتوو: Future.wait
If you need three downloads that do not depend on each other, do not await them one by one. Start all three and wait for all of them together with Future.wait:
ئەگەر سێ پێویست بێت کە پشت بە یەکتر نابەستن، یەک لەدوای یەک چاوەڕێیان مەکە. هەر سێکیان دەست پێ بکە و بە Future.wait پێکەوە چاوەڕێی هەموویان بکە:
Future<String> download(String name, int seconds) async {
await Future.delayed(Duration(seconds: seconds));
return '$name (${seconds}s)';
}
Future<void> main() async {
final watch = Stopwatch()..start();
// One after another: each await waits for the one before
await download('photo', 3);
await download('song', 2);
await download('notes', 1);
print('One by one: ${watch.elapsed.inSeconds} s');
watch.reset();
// Start all three, then wait for all of them together
final results = await Future.wait([
download('photo', 3),
download('song', 2),
download('notes', 1),
]);
print('Together: ${watch.elapsed.inSeconds} s');
print(results);
}One by one: 6 s Together: 3 s [photo (3s), song (2s), notes (1s)]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 10-12
Each
awaitwaits for the previous download first: .هەر
awaitـێک سەرەتا چاوەڕێی پێشوو دەکات: .- Lineدێڕی 18-22
All three Futures are started at once;
Future.waitcompletes when the slowest one does.هەر سێکیان پێکەوە دەست پێ دەکەن؛
Future.waitکاتێک تەواو دەبێت کە خاوترینیان تەواو دەبێت.- Lineدێڕی 24
The results come back as a list, in the order you listed the Futures.
ئەنجامەکان وەک لیستێک دەگەڕێنەوە، بەو ڕیزبەندییەی نووسراون.
This is the same rule as the 28-second and 10-second timeline in the shared lesson: it holds only for independent waits.
ئەمە هەمان یاسای هێڵی کاتی ٢٨ چرکە و ١٠ چرکەیەکەی وانە هاوبەشەکەیە: تەنها بۆ چاوەڕوانیی سەربەخۆ ڕاستە.
Streams: many values over timeتەوژمەکان: چەندین نرخ بە درێژایی کات
A sequence of values (or errors) that arrive one after another over time, such as live database updates, location changes or chat messages. Code listens to a stream and reacts to each new value; a gives one value, a stream many.
زنجیرەیەک نرخ (یان هەڵە)ـە کە یەک لە دوای یەک بە تێپەڕبوونی کات دەگەن، وەک نوێکارییە ڕاستەوخۆکانی بنکەدراوە، گۆڕانی شوێن یان نامەکانی چات. کۆد گوێ لە تەوژمێک دەگرێت و وەڵامی هەر نرخێکی نوێ دەداتەوە؛ یەک نرخ دەدات و تەوژم چەندین نرخ.
A Future gives one value later. A Stream gives many values, one after another: the seconds of a timer, new chat messages, live database updates, the phone's location. You can produce one with an async* function and yield, and read it with await for or listen:
یەک نرخ دواتر دەدات. چەندین نرخ دەدات، یەک لەدوای یەک: چرکەکانی کاتژمێرێک، نامە نوێکانی چات، نوێکردنەوەی ڕاستەوخۆی ، شوێنی مۆبایلەکە. دەتوانیت بە async* و yield یەکێک دروست بکەیت و بە await for یان listen بیخوێنیتەوە:
Stream<int> countdown(int from) async* {
for (var i = from; i >= 1; i--) {
await Future.delayed(const Duration(seconds: 1));
yield i; // send one value into the stream
}
}
Future<void> main() async {
await for (final n in countdown(3)) {
print('$n...');
}
print('Go!');
countdown(2).listen(
(n) => print('listen got $n'),
onDone: () => print('stream closed'),
);
}3... 2... 1... Go! listen got 2 listen got 1 stream closed
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
async*returns aStream<int>instead of a Future.async*لە جیاتیStream<int>ـێک دەگەڕێنێتەوە.- Lineدێڕی 4
yieldsends one value into the stream, then the function continues.yieldیەک نرخ دەنێرێتە نێو ، پاشان بەردەوام دەبێت.- Lineدێڕی 9-11
await forwaits for each value in turn; the loop ends when the stream closes.await forبە نۆرە چاوەڕێی هەر نرخێک دەکات؛ خولەکە کاتێک کۆتایی دێت کە دادەخرێت.- Lineدێڕی 14-17
listenregisters callbacks: one for every value, one when the stream is done.listenتۆمار دەکات: یەکێک بۆ هەر نرخێک و یەکێک کاتێک تەواو دەبێت.
- A normal (single-subscription) stream can be listened to once, for example the bytes of a file.
- A broadcast stream can have many listeners, for example button clicks; a listener only gets the values sent while it listens.
- Like a Future, a stream can also deliver an error; with
await forit is thrown, sotry/catchworks here too.
- ئاسایی (تاک-بەشداربوو) تەنها یەک جار گوێی لێ دەگیرێت، بۆ نموونە بایتەکانی .
- بڵاوکراوە دەتوانێت چەندین هەبێت، بۆ نموونە کرتەکردنی ؛ تەنها ئەو نرخانە وەردەگرێت کە لە کاتی گوێگرتنیدا دەنێردرێن.
- وەک ، دەتوانێت بگەیەنێت؛ لەگەڵ
await forفڕێ دەدرێت، بۆیەtry/catchلێرەشدا کار دەکات.
Heavy computing: a second isolateژماردنی قورس: isolateـی دووەم
Dart's unit of running code: it has its own memory and its own , and isolates talk only by sending messages. Heavy work can run in a second isolate so that the UI stays .
یەکەی کارکردنی کۆدە لە Dartـدا: بیرگە و تایبەت بە خۆی هەیە و isolateـەکان تەنها بە ناردنی پەیام قسە لەگەڵ یەکتر دەکەن. کاری قورس دەتوانرێت لە isolateـێکی دووەمدا کار بکات بۆ ئەوەی ڕووکارەکە بمێنێتەوە.
async and await help with waiting. They do not help with computing: a long calculation inside main keeps the only event loop busy, and the app freezes just as with sleep. For heavy work, Dart can start a second isolate. Each isolate has its own memory and its own event loop, and isolates talk only by sending messages, so they can run at the same time on different processor cores. Isolate.run is the simple way: run one function in a new isolate and get its result as a Future.
async و await یارمەتی چاوەڕوانی دەدەن. یارمەتی ژماردن نادەن: ژماردنێکی درێژ لەنێو mainـدا تاکە سەرقاڵ دەکات و هەروەک sleep گیر دەخوات. بۆ کاری قورس، دەتوانێت دووەم دەست پێ بکات. هەر و خۆی هەیە و تەنها بە ناردنی پەیام قسە لەگەڵ یەکتر دەکەن، بۆیە دەتوانن لە هەمان کاتدا لەسەر جیاواز کار بکەن. Isolate.run ڕێگا سادەکەیە: لە نوێدا جێبەجێ دەکات و ئەنجامەکەی وەک دەداتەوە.
import 'dart:isolate';
int sumTo(int n) {
var total = 0;
for (var i = 1; i <= n; i++) {
total += i;
}
return total;
}
Future<void> main() async {
print('Heavy work goes to another isolate...');
final total = await Isolate.run(() => sumTo(300000000));
print('Sum: $total');
}Heavy work goes to another isolate... Sum: 45000000150000000
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 13
The loop of 300 million additions runs in a new isolate;
main's isolate only awaits the result.خولەکەی ٣٠٠ ملیۆن کۆکردنەوە لە نوێدا جێبەجێ دەبێت؛
mainتەنها چاوەڕێی ئەنجامەکە دەکات.
Why heavy work freezes the UI thread and how Isolate.run moves it to a second isolate, with a JSON example.
بۆچی کاری قورس دەبێتە هۆی و Isolate.run چۆن ئەو کارە دەگوازێتەوە بۆ دووەم، بە نموونەیەکی .
Whole video (2:13), official "Technique of the Week" (April 2024).
هەموو ڤیدیۆکە (2:13)، لە زنجیرە فەرمییەکەی Technique of the Week (نیسانی 2024).
Preview: FutureBuilder and StreamBuilderیەکەم سەیر: FutureBuilder و StreamBuilder
In a Flutter app you rarely print a Future; you show it. FutureBuilder is a widget that rebuilds itself as its Future changes state, and gives you a snapshot to decide what to draw: a spinner while waiting, the data when it arrives, or an error message.
لە Flutterـدا بە دەگمەن چاپ دەکەیت؛ پیشانی دەدەیت. FutureBuilder کە کاتێک دۆخی دەگۆڕێت خۆی دووبارە دروست دەکاتەوە و snapshotـێکت دەداتێ بۆ ئەوەی بڕیار بدەیت چی بکێشیت: بازنەیەکی چاوەڕوانی لە کاتی چاوەڕێکردندا، دراوەکە کاتێک دەگات، یان پەیامی .
import 'package:flutter/material.dart';
Future<String> loadGreeting() async {
await Future.delayed(const Duration(seconds: 2)); // pretend: a server call
return 'Welcome back, Shilan!';
}
class GreetingScreen extends StatefulWidget {
const GreetingScreen({super.key});
@override
State<GreetingScreen> createState() => _GreetingScreenState();
}
class _GreetingScreenState extends State<GreetingScreen> {
late final Future<String> _greeting;
@override
void initState() {
super.initState();
_greeting = loadGreeting(); // start the work once, not in build()
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _greeting,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
return Center(child: Text(snapshot.data!));
},
);
}
}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 16
The Future is kept in the State object…
لە هەڵدەگیرێت…
- Lineدێڕی 21
…and started once, in
initState. Never create it insidebuild:buildcan run many times, and each run would start the work again.…و یەک جار دەست پێ دەکات، لە
initState. هەرگیز لەنێوbuildـدا دروستی مەکە:buildدەکرێت چەندین جار جێبەجێ ببێت و هەر جارێک کارەکە سەرلەنوێ دەست پێ دەکاتەوە.- Lineدێڕی 29-31
Not done yet: show a progress spinner.
هێشتا تەواو نەبووە: بازنەی چاوەڕوانی پیشان بدە.
- Lineدێڕی 32-34
Completed with an error.
بە تەواو بووە.
- Lineدێڕی 35
Completed with a value:
snapshot.data.بە نرخێک تەواو بووە:
snapshot.data.
FutureBuilder بە درێژایی کات سێ شاشەی جیاواز دەکێشێت.CêITPreview: FutureBuilder and StreamBuilderیەکەم سەیر: FutureBuilder و StreamBuilder
StreamBuilder: a new build for every valueStreamBuilder: build بۆ هەر نرخێکی نوێ
StreamBuilder does the same for a Stream: it rebuilds every time a new value arrives. (Here the stream is made once, as a field of the State object, for the same reason.)
StreamBuilder هەمان کار بۆ دەکات: هەموو جارێک کە نرخێکی نوێ دەگات دووبارە دروست دەبێتەوە. (لێرەدا یەک جار دروست دەکرێت، وەک ، بە هەمان هۆکار.)
import 'package:flutter/material.dart';
class SecondsCounter extends StatefulWidget {
const SecondsCounter({super.key});
@override
State<SecondsCounter> createState() => _SecondsCounterState();
}
class _SecondsCounterState extends State<SecondsCounter> {
// One value every second: 1, 2, 3, ...
final Stream<int> _ticks =
Stream.periodic(const Duration(seconds: 1), (i) => i + 1);
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: _ticks,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Text('Waiting for the first tick...');
}
return Text('Seconds on this screen: ${snapshot.data}');
},
);
}
}Conclusion: regular and future functionsدەرئەنجام: کرداری ئاسایی و داهاتوویی
Now the paper's conclusion can be said exactly. A regular function, as in other programming languages, runs at once and returns its result directly (or returns nothing, void). While it runs, its caller stops and waits. A future function (an async function) is for work whose result needs time: it returns a Future at once, and the result is delivered later. While that work is waiting, the program does not stop.
ئێستا دەتوانین دەرئەنجامی نووسینەکە بە وردی بڵێین. ئاسایی، هەروەک لە تردا، یەکسەر جێبەجێ دەبێت و ئەنجامەکەی ڕاستەوخۆ دەگەڕێنێتەوە (یان هیچ ناگەڕێنێتەوە، void). لە کاتی کارکردنیدا بانگکەرەکەی دەوەستێت و چاوەڕێ دەکات. داهاتوویی () بۆ ئەو کارەیە کە ئەنجامەکەی کاتی پێویستە: یەکسەر دەگەڕێنێتەوە و ئەنجامەکە دواتر دەگات. لە کاتێکدا ئەو کارە چاوەڕێ دەکات، ناوەستێت.
Conclusion: regular and future functionsدەرئەنجام: کرداری ئاسایی و داهاتوویی
Regular and future functions side by sideکرداری ئاسایی و داهاتوویی لە تەنیشت یەکەوە
| Aspectلایەن | Regular function ئاسایی | Future (async) function داهاتوویی () |
|---|---|---|
| Declared asناساندن | int add(int a, int b) | Future<int> add(int a, int b) async |
| Returnsدەگەڕێنێتەوە | The value itself, at onceخودی نرخەکە، یەکسەر | A Future at once; the value laterیەکسەر ؛ نرخەکە دواتر |
| Getting the resultوەرگرتنی ئەنجام | final x = add(5, 10);final x = add(5, 10); | final x = await add(5, 10); or .then(...)final x = await add(5, 10); یان .then(...) |
| While it worksلە کاتی کارکردنیدا | The caller waits; a slow one freezes the appبانگکەر چاوەڕێ دەکات؛ ئەگەر خاو بێت گیر دەخات | Only an awaiting caller waits; the event loop stays freeتەنها بانگکەری چاوەڕوان چاوەڕێ دەکات؛ ئازاد دەمێنێتەوە |
| Use it forبۆ چی | Quick work: maths, formatting textکاری خێرا: بیرکاری، دەق | Waiting: network, files, databases, timersچاوەڕوانی: ، ، ، کاتژمێر |
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوو دەدات | Fixچاکردنەوە |
|---|---|---|
final name = loadName(); // no await | name is a Future; printing shows Instance of 'Future<String>'.name ؛ چاپکردنی Instance of 'Future<String>' پیشان دەدات. | final name = await loadName(); inside an async function.final name = await loadName(); لەنێو asyncـدا. |
void main() { await f(); } | Compile-time error: await outside an async function.: await لە دەرەوەی . | Future<void> main() async { await f(); }Future<void> main() async { await f(); } |
await a(); await b(); await c(); // independent | Works, but takes the sum of the three waits.کار دەکات، بەڵام کۆی سێ چاوەڕوانییەکە دەخایەنێت. | await Future.wait([a(), b(), c()]);await Future.wait([a(), b(), c()]); |
await fetch(); // no try/catch | A failure becomes an unhandled exception.شکستێک دەبێتە مامەڵەنەکراو. | Wrap it in try/catch and show a message.لەنێو try/catchـدا دایبنێ و پەیامێک پیشان بدە. |
FutureBuilder(future: load(), ...) // in build | The work restarts on every rebuild.کارەکە لە هەر دووبارە دروستکردنەوەیەکدا سەرلەنوێ دەست پێ دەکاتەوە. | Create the Future once in initState and keep it in a field. یەک جار لە initStateـدا دروست بکە و لە هەڵیبگرە. |
sleep(...) / a huge loop on the main isolate | The app freezes; async does not help. گیر دەخوات؛ async یارمەتی نادات. | Wait with Futures; compute in another isolate (Isolate.run).بە چاوەڕێ بکە؛ لە تردا بژمێرە (Isolate.run). |
Exercisesڕاهێنانەکان
Without running it, write the five letters in the order they are printed. Explain why.
بەبێ جێبەجێکردن، پێنج پیتەکە بەو ڕیزبەندییەی چاپ دەکرێن بنووسە. هۆکارەکەی ڕوون بکەرەوە.
Future<void> greet() async {
print('B');
await Future.delayed(const Duration(seconds: 1));
print('D');
}
Future<void> main() async {
print('A');
final f = greet();
print('C');
await f;
print('E');
}Show answerوەڵامەکە پیشان بدە
A
B
C
D
E- A: the first line of
main. - B: calling
greet()runs its code at once, until itsawait. - C:
greetpaused,maincontinues (it has not awaited yet). - D:
mainnow awaitsf; after 1 sgreetresumes and prints D. - E: the Future
fis complete, somaingoes on.
- A: یەکەم دێڕی
main. - B: بانگکردنی
greet()کۆدەکەی یەکسەر جێبەجێ دەکات، تاawaitـەکەی. - C:
greetڕاوەستا،mainبەردەوام دەبێت (هێشتاawaitـی نەکردووە). - D:
mainئێستاawaitـیfدەکات؛ دوای ١ چرکەgreetبەردەوام دەبێت و D چاپ دەکات. - E:
fتەواو بووە، بۆیەmainبەردەوام دەبێت.
This program prints Students: Instance of 'Future<int>'. Make it print Students: 32.
ئەم Students: Instance of 'Future<int>' چاپ دەکات. وای لێ بکە Students: 32 چاپ بکات.
Future<int> countStudents() async {
await Future.delayed(const Duration(milliseconds: 300)); // a database query
return 32;
}
void main() {
final n = countStudents();
print('Students: $n');
}Students: Instance of 'Future<int>'
Show answerوەڵامەکە پیشان بدە
Future<int> countStudents() async {
await Future.delayed(const Duration(milliseconds: 300)); // a database query
return 32;
}
Future<void> main() async {
final n = await countStudents();
print('Students: $n');
}Students: 32
Two changes: await before the call, and main becomes Future<void> main() async.
دوو گۆڕانکاری: await لە پێش بانگکردنەکە و main دەبێتە Future<void> main() async.
then()ـەوە بۆ awaitRewrite main with async, await and try/catch. The output must stay the same.
main بە async، await و try/catch بنووسەرەوە. دەبێت وەک خۆی بمێنێتەوە.
Future<int> fetchPrice(String item) async {
await Future.delayed(const Duration(milliseconds: 500));
if (item == 'gold') throw Exception('price service is offline');
return 1500;
}
void main() {
fetchPrice('gold')
.then((p) => print('Price: $p IQD'))
.catchError((e) => print('Failed: $e'));
}Failed: Exception: price service is offline
Show answerوەڵامەکە پیشان بدە
Future<int> fetchPrice(String item) async {
await Future.delayed(const Duration(milliseconds: 500));
if (item == 'gold') throw Exception('price service is offline');
return 1500;
}
Future<void> main() async {
try {
final p = await fetchPrice('gold');
print('Price: $p IQD');
} catch (e) {
print('Failed: $e');
}
}Failed: Exception: price service is offline
Exercisesڕاهێنانەکان
More exercisesڕاهێنانی زیاتر
A school app loads the timetable (2 s), the library list (4 s) and the news (1 s). The three requests do not depend on each other. How long does it take one by one, and with Future.wait? Check your answer by running the code.
قوتابخانە خشتەی وانەکان (٢ چرکە)، لیستی کتێبخانە (٤ چرکە) و هەواڵەکان (١ چرکە) بار دەکات. سێ پشت بە یەکتر نابەستن. یەک لەدوای یەک چەند دەخایەنێت و بە Future.wait چەند؟ بە جێبەجێکردنی کۆدەکە وەڵامەکەت بپشکنە.
Show answerوەڵامەکە پیشان بدە
Future<String> request(String name, int seconds) async {
await Future.delayed(Duration(seconds: seconds));
return name;
}
Future<void> main() async {
final watch = Stopwatch()..start();
await request('timetable', 2);
await request('library', 4);
await request('news', 1);
print('One by one: ${watch.elapsed.inSeconds} s');
watch.reset();
await Future.wait([request('timetable', 2), request('library', 4), request('news', 1)]);
print('Future.wait: ${watch.elapsed.inSeconds} s');
}One by one: 7 s Future.wait: 4 s
Explain the difference between a regular function and a future function in your own words, with one Dart example of each.
جیاوازیی نێوان ئاسایی و داهاتوویی بە وشەی خۆت ڕوون بکەرەوە، بە یەک نموونەی بۆ هەریەکەیان.
Show answerوەڵامەکە پیشان بدە
A regular function, for example int addNumbers(int a, int b) => a + b;, returns its value directly; its caller waits while it runs, which is fine because it is quick. A future function, for example Future<String> readFile(String name) async { ... }, returns a Future at once and delivers the value later; the caller gets it with await (or then), and while it waits the event loop keeps the app responsive.
ئاسایی، بۆ نموونە int addNumbers(int a, int b) => a + b;، نرخەکەی ڕاستەوخۆ دەگەڕێنێتەوە؛ بانگکەرەکەی لە کاتی کارکردنیدا چاوەڕێ دەکات، کە کێشە نییە چونکە خێرایە. داهاتوویی، بۆ نموونە Future<String> readFile(String name) async { ... }، یەکسەر دەگەڕێنێتەوە و نرخەکە دواتر دەگەیەنێت؛ بانگکەر بە await (یان then) وەریدەگرێت و لە کاتی چاوەڕوانیدا دەهێڵێتەوە.
Summaryپوختە
Future<T>(a class ofdart:async) is a value that arrives later: first uncompleted, then completed with a value or an error.asyncmakes a function return a Future;await, only inside it, pauses that function until the Future completes.- One isolate runs one thing at a time; its event loop serves taps, timers and frames while awaiting functions are parked.
- Forgetting
awaitgivesInstance of 'Future<...>'. Errors:try/catch/finallyaroundawait, orthen/catchError. Future.waitoverlaps independent waits (the total is the longest one); dependent steps stay in order.- A Stream gives many values over time (
async*,yield,await for,listen). Heavy computing goes to another isolate. - In Flutter,
FutureBuilder/StreamBuilderdraw waiting, data and error states; create their Future/Stream once, not inbuild.
Future<T>(dart:async) نرخێکە کە دواتر دێت: سەرەتا تەواونەبوو، پاشان تەواوبوو بە نرخێک یان .asyncوا دەکات بگەڕێنێتەوە؛await، تەنها لەنێویدا، ئەو ڕادەگرێت تا تەواو دەبێت.- یەک لە یەک کاتدا یەک کار دەکات؛ ئەو خزمەتی دەستلێدان، کاتژمێر و وێنەکان دەکات لە کاتێکدا چاوەڕوانەکان ڕاگیراون.
- لەبیرکردنی
awaitئەنجامیInstance of 'Future<...>'دەدات. :try/catch/finallyلە دەوریawait، یانthen/catchError. Future.waitچاوەڕوانیی سەربەخۆ پێکەوە دەکات (کۆی گشتی درێژترینیانە)؛ هەنگاوی بەستراو بە ڕیزبەندی دەمێنێتەوە.- چەندین نرخ بە درێژایی کات دەدات (
async*،yield،await for،listen). ژماردنی قورس دەچێتە ترەوە. - لە Flutterـدا،
FutureBuilder/StreamBuilderدۆخەکانی چاوەڕوانی، دراوە و دەکێشن؛ / یەک جار دروست بکە، نەک لەbuildـدا.
What is the difference between a regular and a future function?جیاوازیی نێوان کرداری ئاسایی و داهاتوویی چییە؟
A regular function returns its result at once while its caller waits. A future (async) function returns a Future at once and the result later; while it waits, the event loop keeps the app responsive.
ئاسایی ئەنجامەکەی یەکسەر دەگەڕێنێتەوە لە کاتێکدا بانگکەرەکەی چاوەڕێ دەکات. داهاتوویی (async) یەکسەر و دواتر ئەنجامەکە دەگەڕێنێتەوە؛ لە کاتی چاوەڕوانیدا دەهێڵێتەوە.
Does await freeze the app?ئایا await ئەپەکە گیر دەخات؟
No. It pauses only its own function; the event loop keeps handling other events.
نەخێر. تەنها خۆی ڕادەگرێت؛ بەردەوام ڕووداوەکانی تر بەڕێوە دەبات.
When is Future.wait faster than awaiting one by one?کەی Future.wait لە چاوەڕوانیی یەک لەدوای یەک خێراترە؟
When the tasks are independent waits (network, disk). The total becomes the longest wait instead of the sum.
کاتێک ئەرکەکان چاوەڕوانیی سەربەخۆن (، دیسک). کۆی گشتی دەبێتە درێژترین چاوەڕوانی لە جیاتی کۆکراوەکەیان.
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Widgets and the Widget Treeویجێتەکان و داری ویجێتەکان
Related lecturesوانە پەیوەندیدارەکان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.