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.

25 min read24 خولەک خوێندنەوە · 24 stepsهەنگاو

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 await correctly, and predict the order of output of async code.
  • Describe the event loop and why await pauses 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: نرخێک کە دواتر دێت

Definitionپێناسە

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> دەگەڕێنێتەوە.

An uncompleted Future<int> box with two arrows: one to 'completed with a value: 15', one to 'completed with an error: Exception(offline)'.سندوقی Future<int>ـێکی تەواونەبوو بە دوو تیر: یەکێکیان بۆ «تەواوبوو بە نرخێک: 15» و ئەوی تر بۆ «تەواوبوو بە هەڵەیەک: Exception(offline)».
A Future starts uncompleted and ends with a value or an error. بە تەواونەبوویی دەست پێ دەکات و بە نرخێک یان کۆتایی دێت.CêIT
Quick checkپشکنینی خێراA Future<String> has just been returned by a function that downloads a page. What is its state? کە پەڕەیەک دەکات تازە Future<String>ـێکی گەڕاندۆتەوە. دۆخەکەی چییە؟

Flutter Course for Beginners – 37-hour Cross Platform App Development TutorialfreeCodeCamp.org · Englishئینگلیزی · 3.8M viewsبینین · 75K likesلایک · Partبەشی 4:30:02–4:33:57 (ofلە 36:39:22)

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کلاسێک، نەک وشەی کلیلەیی: پسوولەکە

The kebab shop 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.

پسوولە دەکرێت ون ببێت یان بۆ هەمیشە بمێنێتەوە؛ هەمیشە یەک جار تەواو دەبێت و بە وردی بە کۆدەکەت دەڵێت کەی.

Quick checkپشکنینی خێراWhat is Future in Dart?Future لە چییە؟

async and awaitasync و await

Definitionپێناسە

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 async marks a function as asynchronous. Every async function automatically returns a Future: Future<int>, Future<String> or Future<void>.
  • The word await can be used only inside an async function. The functions you call inside an async function do not all need await, only the ones whose result you must wait for.
  • A call marked with await stops 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 (or then, 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:

نموونەکەی خودی نووسینەکە دوو ژمارە لە کۆ دەکاتەوە:

DART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

async makes the return type Future<int>, although the body just returns an int.

async جۆری دەکات بە Future<int>، هەرچەندە جەستەکە تەنها intـێک دەگەڕێنێتەوە.

Lineدێڕی 6

await unwraps the Future and gives the plain int 15.

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 وەری دەگریت:

DART
// 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');
}
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

await waits for the Future and takes the 15 out of it.

await چاوەڕێی دەکات و ⁦15⁩ـەکەی لێ دەردەهێنێت.

Quick checkپشکنینی خێراWhere can you write await?لە کوێ دەتوانیت await بنووسیت؟

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. لەوێ ڕادەوەستێت، دەداتەوە بە بانگکەر و بانگکەر بەردەوام دەبێت.

DART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

Runs at once, as part of the call on line 9.

یەکسەر جێبەجێ دەبێت، وەک بەشێک لە بانگکردنەکەی دێڕی ٩.

Lineدێڕی 3

makeTea pauses here; control goes back to main.

makeTea لێرەدا ڕادەوەستێت؛ کۆنترۆڵ دەگەڕێتەوە بۆ main.

Lineدێڕی 10

main did not wait (no await), so it prints line 3 now.

main چاوەڕێی نەکرد (await نییە)، بۆیە ئێستا دێڕی ٣ چاپ دەکات.

Lineدێڕی 4

Two seconds later the timer event arrives and makeTea finishes.

دوو چرکە دواتر ڕووداوی کاتژمێرەکە دەگات و 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).

ئەمە چایچییەکەی وانە هاوبەشەکەیە بە کۆد: کترییەکە دادەنرێت (٢)، چایچییەکە داواکاریی دواتر وەردەگرێت (٣) و چاییەکە کاتێک ئامادە بوو پێشکەش دەکرێت (٤).

Quick checkپشکنینی خێراIn the tea example, why is "3. Taking the next order" printed before "4. Tea is ready"?لە نموونەی چاییەکەدا، بۆچی "⁦3. Taking the next order⁩" پێش "⁦4. Tea is ready⁩" چاپ دەکرێت؟

The paper's file example, made runnableنموونەی فایلەکەی نووسینەکە، بە شێوەیەکی جێبەجێکراو

The paper shows the same task twice, first without and then with async and await:

نووسینەکە هەمان ئەرک دوو جار پیشان دەدات، سەرەتا بەبێ و پاشان بە async و awaitـەوە:

As in the paper: without async and awaitوەک لە نووسینەکەدا: بەبێ async و awaitDART
void main() {
       print("Start");
       data = readFile("file.txt");  // This takes time
       processData(data);
       print("End");
}
As in the paper: with async and awaitوەک لە نووسینەکەدا: بە async و awaitـەوەDART
void main() async {
       print("Start");
       data = await readFile("file.txt");  // This takes time but doesn't block
       processData(data);
       print("End");
}
Quick checkپشکنینی خێراWhy does dart run stop on both of the paper's snippets?بۆچی dart run لەسەر هەردوو پارچە کۆدەکەی نووسینەکە دەوەستێت؟

The paper's file example, made runnableنموونەی فایلەکەی نووسینەکە، بە شێوەیەکی جێبەجێکراو

The runnable version: who really waits?وەشانە جێبەجێکراوەکە: کێ بەڕاستی چاوەڕێ دەکات؟

The runnable versionوەشانە جێبەجێکراوەکەDART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1-4

readFile returns a Future<String> that completes after 3 seconds.

readFile Future<String>ـێک دەگەڕێنێتەوە کە دوای ٣ چرکە تەواو دەبێت.

Lineدێڕی 10

A timer: its callback is an event that will be due after 1 second.

کاتژمێرێک: کە دوای ١ چرکە کاتی دێت.

Lineدێڕی 11

main pauses here for 3 seconds, but the event loop is free.

main لێرەدا ٣ چرکە ڕادەوەستێت، بەڵام ئازادە.

Lineدێڕی 12-13

Only after the Future completes does main continue: Processing, then End.

تەنها دوای تەواوبوونی main بەردەوام دەبێت: Processing، پاشان End.

Quick checkپشکنینی خێراIn the runnable version, what is true while main waits at await readFile(...)?لە وەشانە جێبەجێکراوەکەدا، لە کاتێکدا main لە await readFile(...) چاوەڕێ دەکات چی ڕاستە؟

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 هەموو شت ڕادەگرێت. ئەمە هەمان بە خوێندنەوەیەکی ڕێگر و هەمان کاتژمێری ١ چرکەیی:

DART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

sleep freezes 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 main is 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ـدا بەکار مەهێنە.

Quick checkپشکنینی خێراIn the blocking version, why does the 1-second timer print last?لە وەشانە ڕێگرەکەدا، بۆچی کاتژمێری ١ چرکەیی لە کۆتاییدا چاپ دەکات؟

The event loop: one thing at a timeخولی ڕووداوەکان: یەک کار لە یەک کاتدا

Definitionپێناسە

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 دەتوانێت چاوەڕێ بکات لە کاتێکدا کاتژمێرەکە کار دەکات، ئەگەر لە یەک کاتدا تەنها یەک کار بکات؟ هەموو کۆدێکی لەنێو جێبەجێ دەبێت. هەر یەک و یەک هەیە. دەستلێدان، کاتژمێر، دووبارە کێشانەوەی شاشە و پەیامی « ئامادەیە» هەموویان کە لە چاوەڕێ دەکەن. ڕووداوی دواتر وەردەگرێت، کۆدەکەی تا کۆتایی جێبەجێ دەکات و پاشان ڕووداوی دواتر وەردەگرێت.

Quick checkپشکنینی خێراWhich sentence about Dart's event loop is correct?کام ڕستە دەربارەی ڕاستە؟

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ـەوە بەردەوام دەبێت. سەیری جێبەجێبوونی نموونەکەی نووسینەکە بکە:

Animation in six steps beside the code of the runnable example: main prints Start; at await main parks and readFile's Future waits, uncompleted; the event loop takes a repaint and a tap from the queue; after 1 second the timer event runs and prints its line; after 3 seconds the Future completes; main continues and prints Processing and End.
Animation in six steps beside the code of the runnable example: main prints Start; at await main parks and readFile's Future waits, uncompleted; the event loop takes a repaint and a tap from the queue; after 1 second the timer event runs and prints its line; after 3 seconds the Future completes; main continues and prints Processing and End.
The event loop takes one event at a time; the awaiting function waits outside the loop. یەک ڕووداو لە یەک کاتدا وەردەگرێت؛ چاوەڕوانەکە لە دەرەوەی چاوەڕێ دەکات.CêIT
Quick checkپشکنینی خێراA function reaches await on a Future that is not complete yet. What does it do? دەگاتە 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 بانگ بکەیت، خودی وەردەگریت، پسوولەکە، نەک نرخەکە:

DART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 8

No await: data is a Future<String>, so print shows the object, not the text.

await نییە: data Future<String>ـێکە، بۆیە print پیشان دەدات، نەک دەقەکە.

Fixed: await, and main is asyncچاککراو: await و mainـی asyncDART
Future<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');
}
Quick checkپشکنینی خێراA program prints Instance of 'Future<String>' where you expected a name. What is the likely fix? Instance of 'Future<String>' چاپ دەکات لە شوێنێک کە چاوەڕێی ناوێکت دەکرد. چاکردنەوەی گونجاو چییە؟

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 لە کۆتاییدا لە هەردوو حاڵەتدا جێبەجێ دەبێت:

DART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7-10

Three callbacks are registered; none of them runs yet.

سێ تۆمار دەکرێن؛ هیچیان هێشتا جێبەجێ نابن.

Lineدێڕی 11

main does 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 تەنها بۆ کۆدی کورتی یەک دێڕی بەکار دەهێنێت.

The same logic with awaitهەمان لۆجیک بە awaitDART
Future<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.');
  }
}
Quick checkپشکنینی خێراIn the then example, why is "main has reached its last line" printed before the weather?لە نموونەی thenـدا، بۆچی "⁦main has reached its last line⁩" پێش کەشوهەواکە چاپ دەکرێت؟

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 لە هەردوو حاڵەتدا جێبەجێ دەبێت.

DART
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');
    }
  }
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

throw inside an async function completes its Future with an error.

throw لەنێو بە تەواو دەکات.

Lineدێڕی 12

The error appears here, at the await, and jumps to catch.

لێرە، لە awaitـدا دەردەکەوێت و باز دەدات بۆ catch.

Lineدێڕی 16-18

finally runs after success and after failure.

finally دوای سەرکەوتن و دوای شکستیش جێبەجێ دەبێت.

If nobody catches the error, the program crashes with an unhandled exception (the path is shortened here):

ئەگەر کەس نەگرێت، بە مامەڵەنەکراو دەکەوێت (ڕێڕەوەکە لێرەدا کورت کراوەتەوە):

DART
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');
}
Quick checkپشکنینی خێراfinal price = await fetchPrice('gold'); throws. Where does the error go?final price = await fetchPrice('gold'); فڕێ دەدات. بۆ کوێ دەچێت؟

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 پێکەوە چاوەڕێی هەموویان بکە:

DART
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);
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10-12

Each await waits for the previous download first: 3+2+13 + 2 + 1.

هەر awaitـێک سەرەتا چاوەڕێی پێشوو دەکات: 3+2+13 + 2 + 1.

Lineدێڕی 18-22

All three Futures are started at once; Future.wait completes when the slowest one does.

هەر سێکیان پێکەوە دەست پێ دەکەن؛ Future.wait کاتێک تەواو دەبێت کە خاوترینیان تەواو دەبێت.

Lineدێڕی 24

The results come back as a list, in the order you listed the Futures.

ئەنجامەکان وەک لیستێک دەگەڕێنەوە، بەو ڕیزبەندییەی نووسراون.

Timeline from 0 to 6 seconds. Top: photo 0 to 3 s, song 3 to 5 s, notes 5 to 6 s, total 6 s. Bottom with Future.wait: photo, song and notes all start at 0 and end at 3, 2 and 1 s, total 3 s.هێڵی کات لە ٠ بۆ ٦ چرکە. سەرەوە: photo لە ٠ بۆ ٣ چرکە، song لە ٣ بۆ ٥، notes لە ٥ بۆ ٦، کۆی گشتی ٦ چرکە. خوارەوە بە Future.wait: photo، song و notes هەموویان لە ٠ دەست پێ دەکەن و لە ٣، ٢ و ١ چرکەدا کۆتایی دێن، کۆی گشتی ٣ چرکە.
Independent waits overlap: the total is the longest one.چاوەڕوانیی سەربەخۆ پێکەوە دەبن: کۆی گشتی درێژترینیانە.CêIT
Tone by one=3+2+1=6 sTFuture.wait=max⁡(3,2,1)=3 s\begin{aligned} T_{\text{one by one}} &= 3 + 2 + 1 = 6\ \text{s} \\ T_{\text{Future.wait}} &= \max(3, 2, 1) = 3\ \text{s} \end{aligned}

This is the same rule as the 28-second and 10-second timeline in the shared lesson: it holds only for independent waits.

ئەمە هەمان یاسای هێڵی کاتی ٢٨ چرکە و ١٠ چرکەیەکەی وانە هاوبەشەکەیە: تەنها بۆ چاوەڕوانیی سەربەخۆ ڕاستە.

Quick checkپشکنینی خێراThree independent requests take 2 s, 4 s and 1 s. About how long does await Future.wait([...]) take?سێ سەربەخۆ ٢ چرکە، ٤ چرکە و ١ چرکە دەخایەنن. await Future.wait([...]) نزیکەی چەند دەخایەنێت؟

Streams: many values over timeتەوژمەکان: چەندین نرخ بە درێژایی کات

Definitionپێناسە

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 بیخوێنیتەوە:

DART
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'),
  );
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 1

async* returns a Stream<int> instead of a Future.

async* لە جیاتی Stream<int>ـێک دەگەڕێنێتەوە.

Lineدێڕی 4

yield sends one value into the stream, then the function continues.

yield یەک نرخ دەنێرێتە نێو ، پاشان بەردەوام دەبێت.

Lineدێڕی 9-11

await for waits for each value in turn; the loop ends when the stream closes.

await for بە نۆرە چاوەڕێی هەر نرخێک دەکات؛ خولەکە کاتێک کۆتایی دێت کە دادەخرێت.

Lineدێڕی 14-17

listen registers 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 for it is thrown, so try/catch works here too.
  • ئاسایی (تاک-بەشداربوو) تەنها یەک جار گوێی لێ دەگیرێت، بۆ نموونە بایتەکانی .
  • بڵاوکراوە دەتوانێت چەندین هەبێت، بۆ نموونە کرتەکردنی ؛ تەنها ئەو نرخانە وەردەگرێت کە لە کاتی گوێگرتنیدا دەنێردرێن.
  • وەک ، دەتوانێت بگەیەنێت؛ لەگەڵ await for فڕێ دەدرێت، بۆیە try/catch لێرەشدا کار دەکات.
Quick checkپشکنینی خێراYou need the user's location every time it changes. Which type fits?هەموو جارێک کە شوێنی دەگۆڕێت پێویستت پێیەتی. کام جۆر گونجاوە؟

Heavy computing: a second isolateژماردنی قورس: isolateـی دووەم

Definitionپێناسە

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 ڕێگا سادەکەیە: لە نوێدا جێبەجێ دەکات و ئەنجامەکەی وەک دەداتەوە.

DART
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');
}
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 13

The loop of 300 million additions runs in a new isolate; main's isolate only awaits the result.

خولەکەی ٣٠٠ ملیۆن کۆکردنەوە لە نوێدا جێبەجێ دەبێت؛ main تەنها چاوەڕێی ئەنجامەکە دەکات.

Quick checkپشکنینی خێراYour app must resize a large photo, which takes 2 seconds of pure calculation. What keeps the screen smooth? دەبێت وێنەیەکی گەورە بچووک بکاتەوە، کە ٢ چرکە ژماردنی پەتی دەخایەنێت. چی شاشەکە نەرم دەهێڵێتەوە؟

Isolates (Technique of the Week)Flutter · Englishئینگلیزی · 109K viewsبینین · 4.2K likesلایک

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ـێکت دەداتێ بۆ ئەوەی بڕیار بدەیت چی بکێشیت: بازنەیەکی چاوەڕوانی لە کاتی چاوەڕێکردندا، دراوەکە کاتێک دەگات، یان پەیامی .

DARTRuns on a phone (or an emulator)لەسەر مۆبایل کار دەکات
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 inside build: build can 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.

Three phone screens titled Greeting: a spinning progress circle (ConnectionState.waiting), the text 'Welcome back, Shilan!' (snapshot.hasData), and an error text (snapshot.hasError).سێ شاشەی مۆبایل بە ناونیشانی Greeting: بازنەیەکی چاوەڕوانیی خولاوە (ConnectionState.waiting)، دەقی 'Welcome back, Shilan!' (snapshot.hasData) و دەقێکی هەڵە (snapshot.hasError).
The same FutureBuilder draws three different screens over time.هەمان FutureBuilder بە درێژایی کات سێ شاشەی جیاواز دەکێشێت.CêIT
Quick checkپشکنینی خێراWhy should the Future for a FutureBuilder be created in initState and not inside build?بۆچی دەبێت FutureBuilder لە initStateـدا دروست بکرێت نەک لەنێو buildـدا؟

Preview: FutureBuilder and StreamBuilderیەکەم سەیر: FutureBuilder و StreamBuilder

StreamBuilder: a new build for every value⁦StreamBuilder: 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 هەمان کار بۆ دەکات: هەموو جارێک کە نرخێکی نوێ دەگات دووبارە دروست دەبێتەوە. (لێرەدا یەک جار دروست دەکرێت، وەک ، بە هەمان هۆکار.)

DARTRuns on a phone (or an emulator)لەسەر مۆبایل کار دەکات
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}');
      },
    );
  }
}
Quick checkپشکنینی خێراHow often does a StreamBuilder call its builder?StreamBuilder چەند جار builderـەکەی بانگ دەکات؟

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). لە کاتی کارکردنیدا بانگکەرەکەی دەوەستێت و چاوەڕێ دەکات. داهاتوویی () بۆ ئەو کارەیە کە ئەنجامەکەی کاتی پێویستە: یەکسەر دەگەڕێنێتەوە و ئەنجامەکە دواتر دەگات. لە کاتێکدا ئەو کارە چاوەڕێ دەکات، ناوەستێت.

Quick checkپشکنینی خێراWhich function should be a future (async) function?کام دەبێت داهاتوویی (async) بێت؟

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چاوەڕوانی: ، ، ، کاتژمێر
Quick checkپشکنینی خێراWhat does a future (async) function give back at the moment you call it? داهاتوویی () لە هەمان ساتی بانگکردندا چی دەگەڕێنێتەوە؟

Common mistakesهەڵە باوەکان

MistakeهەڵەWhat happensچی ڕوو دەداتFixچاکردنەوە
final name = loadName(); // no awaitname 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(); // independentWorks, but takes the sum of the three waits.کار دەکات، بەڵام کۆی سێ چاوەڕوانییەکە دەخایەنێت.await Future.wait([a(), b(), c()]);await Future.wait([a(), b(), c()]);
await fetch(); // no try/catchA failure becomes an unhandled exception.شکستێک دەبێتە مامەڵەنەکراو.Wrap it in try/catch and show a message.لەنێو try/catchـدا دایبنێ و پەیامێک پیشان بدە.
FutureBuilder(future: load(), ...) // in buildThe 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 isolateThe app freezes; async does not help. گیر دەخوات؛ async یارمەتی نادات.Wait with Futures; compute in another isolate (Isolate.run).بە چاوەڕێ بکە؛ لە تردا بژمێرە (Isolate.run).

Exercisesڕاهێنانەکان

Exerciseڕاهێنان1. Predict the order١. ڕیزبەندییەکە پێشبینی بکە

Without running it, write the five letters in the order they are printed. Explain why.

بەبێ جێبەجێکردن، پێنج پیتەکە بەو ڕیزبەندییەی چاپ دەکرێن بنووسە. هۆکارەکەی ڕوون بکەرەوە.

DART
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وەڵامەکە پیشان بدە
TEXT
A
B
C
D
E
  • A: the first line of main.
  • B: calling greet() runs its code at once, until its await.
  • C: greet paused, main continues (it has not awaited yet).
  • D: main now awaits f; after 1 s greet resumes and prints D.
  • E: the Future f is complete, so main goes on.
  • A: یەکەم دێڕی main.
  • B: بانگکردنی greet() کۆدەکەی یەکسەر جێبەجێ دەکات، تا awaitـەکەی.
  • C: greet ڕاوەستا، main بەردەوام دەبێت (هێشتا awaitـی نەکردووە).
  • D: main ئێستا awaitـی f دەکات؛ دوای ١ چرکە greet بەردەوام دەبێت و D چاپ دەکات.
  • E: f تەواو بووە، بۆیە main بەردەوام دەبێت.
Exerciseڕاهێنان2. Fix the bug٢. هەڵەکە چاک بکەرەوە

This program prints Students: Instance of 'Future<int>'. Make it print Students: 32.

ئەم Students: Instance of 'Future<int>' چاپ دەکات. وای لێ بکە Students: 32 چاپ بکات.

DART
Future<int> countStudents() async {
  await Future.delayed(const Duration(milliseconds: 300)); // a database query
  return 32;
}

void main() {
  final n = countStudents();
  print('Students: $n');
}
Show answerوەڵامەکە پیشان بدە
DART
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');
}

Two changes: await before the call, and main becomes Future<void> main() async.

دوو گۆڕانکاری: await لە پێش بانگکردنەکە و main دەبێتە Future<void> main() async.

Exerciseڕاهێنان3. From then() to await٣. لە then()ـەوە بۆ await

Rewrite main with async, await and try/catch. The output must stay the same.

main بە async، await و try/catch بنووسەرەوە. دەبێت وەک خۆی بمێنێتەوە.

DART
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'));
}
Show answerوەڵامەکە پیشان بدە
DART
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');
  }
}
Quick checkپشکنینی خێراIn exercise 1, why is B printed before C?لە ڕاهێنانی ١ـدا، بۆچی B پێش C چاپ دەکرێت؟

Exercisesڕاهێنانەکان

More exercisesڕاهێنانی زیاتر

Exerciseڕاهێنان4. How long?٤. چەند دەخایەنێت؟

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وەڵامەکە پیشان بدە
2+4+1=7 smax⁡(2,4,1)=4 s\begin{aligned} 2 + 4 + 1 &= 7\ \text{s} \\ \max(2, 4, 1) &= 4\ \text{s} \end{aligned}
DART
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');
}
Exerciseڕاهێنان5. Regular or future?٥. ئاسایی یان داهاتوویی؟

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) وەریدەگرێت و لە کاتی چاوەڕوانیدا دەهێڵێتەوە.

Quick checkپشکنینی خێراWhich statement is wrong?کام ڕستە هەڵەیە؟

Summaryپوختە

  • Future<T> (a class of dart:async) is a value that arrives later: first uncompleted, then completed with a value or an error.
  • async makes 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 await gives Instance of 'Future<...>'. Errors: try/catch/finally around await, or then/catchError.
  • Future.wait overlaps 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/StreamBuilder draw waiting, data and error states; create their Future/Stream once, not in build.
  • 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ـدا.
Review questionsپرسیارەکانی پێداچوونەوە
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زاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Widgets and the Widget Treeویجێتەکان و داری ویجێتەکان

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.