Skip to content

Commit 4f0b054

Browse files
authored
Merge pull request #17 from mahmoodhamdi:update-readme-and-add-async-programming-answers
Update README and add Asynchronous Programming section
2 parents 176f0fd + 2151865 commit 4f0b054

File tree

2 files changed

+389
-25
lines changed

2 files changed

+389
-25
lines changed
Lines changed: 384 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,384 @@
1+
# Flutter Async Programming: Interview Answers
2+
3+
1. **Future vs Stream in Dart?**
4+
Future represents a single async operation, while Stream is a sequence of async events over time.
5+
6+
2. **Creating a Future in Dart?**
7+
8+
```dart
9+
Future<String> fetchData() async {
10+
return await http.get('https://api.example.com/data');
11+
}
12+
```
13+
14+
3. **Purpose of async and await?**
15+
`async` marks a function as asynchronous, `await` waits for a Future to complete.
16+
17+
4. **Handling errors in async code?**
18+
Use try-catch blocks:
19+
20+
```dart
21+
try {
22+
await fetchData();
23+
} catch (e) {
24+
print('Error: $e');
25+
}
26+
```
27+
28+
5. **Completer in Dart?**
29+
Used to create and complete a Future manually:
30+
31+
```dart
32+
final completer = Completer<String>();
33+
completer.complete('Done');
34+
```
35+
36+
6. **Creating a Stream in Dart?**
37+
38+
```dart
39+
Stream<int> countStream(int max) async* {
40+
for (int i = 1; i <= max; i++) {
41+
yield i;
42+
}
43+
}
44+
```
45+
46+
7. **Single vs broadcast streams?**
47+
Single subscription streams can only be listened to once, broadcast streams allow multiple listeners.
48+
49+
8. **Using StreamBuilder in Flutter?**
50+
51+
```dart
52+
StreamBuilder<int>(
53+
stream: countStream(10),
54+
builder: (context, snapshot) {
55+
if (snapshot.hasData) {
56+
return Text('${snapshot.data}');
57+
}
58+
return CircularProgressIndicator();
59+
},
60+
)
61+
```
62+
63+
9. **FutureBuilder in Flutter?**
64+
Builds widgets based on the latest snapshot of interaction with a Future:
65+
66+
```dart
67+
FutureBuilder<String>(
68+
future: fetchData(),
69+
builder: (context, snapshot) {
70+
if (snapshot.hasData) {
71+
return Text(snapshot.data!);
72+
}
73+
return CircularProgressIndicator();
74+
},
75+
)
76+
```
77+
78+
10. **Cancelling a stream subscription?**
79+
80+
```dart
81+
final subscription = stream.listen((data) {
82+
print(data);
83+
});
84+
subscription.cancel();
85+
```
86+
87+
11. **async* and sync* functions?**
88+
`async*` defines an asynchronous generator (returns Stream), `sync*` defines a synchronous generator (returns Iterable).
89+
90+
12. **Using await with multiple futures?**
91+
92+
```dart
93+
final result1 = await fetchData1();
94+
final result2 = await fetchData2();
95+
```
96+
97+
13. **StreamTransformer?**
98+
Modifies or filters stream events:
99+
100+
```dart
101+
stream.transform(StreamTransformer.fromHandlers(
102+
handleData: (data, sink) {
103+
sink.add('Number: $data');
104+
},
105+
)).listen(print);
106+
```
107+
108+
14. **Handling timeouts in async code?**
109+
110+
```dart
111+
try {
112+
await fetchData().timeout(Duration(seconds: 5));
113+
} on TimeoutException catch (e) {
114+
print('Operation timed out');
115+
}
116+
```
117+
118+
15. **then method in Future?**
119+
Handles successful Future completion:
120+
121+
```dart
122+
fetchData().then((result) {
123+
print('Data: $result');
124+
}).catchError((error) {
125+
print('Error: $error');
126+
});
127+
```
128+
129+
16. **Chaining async operations?**
130+
131+
```dart
132+
fetchData1()
133+
.then((result1) => fetchData2(result1))
134+
.then((result2) => fetchData3(result2));
135+
```
136+
137+
17. **async package?**
138+
Provides additional utilities for Futures and Streams, like AsyncCache and LazyStream.
139+
140+
18. **Implementing Future.delayed?**
141+
142+
```dart
143+
Future.delayed(Duration(seconds: 2), () {
144+
print('Delayed operation');
145+
});
146+
```
147+
148+
19. **rxdart package?**
149+
Extends Dart's Stream API with ReactiveX-inspired operators:
150+
151+
```dart
152+
final subject = BehaviorSubject<int>();
153+
subject.add(1);
154+
subject.stream.listen(print);
155+
```
156+
157+
20. **Handling HTTP requests asynchronously?**
158+
159+
```dart
160+
Future<String> fetchData() async {
161+
final response = await http.get(Uri.parse('https://api.example.com/data'));
162+
if (response.statusCode == 200) {
163+
return response.body;
164+
} else {
165+
throw Exception('Failed to load data');
166+
}
167+
}
168+
```
169+
170+
21. **Future.wait?**
171+
Waits for multiple Futures to complete:
172+
173+
```dart
174+
final results = await Future.wait([fetchData1(), fetchData2(), fetchData3()]);
175+
```
176+
177+
22. **Handling multiple streams with MergeStream?**
178+
179+
```dart
180+
final mergedStream = MergeStream([stream1, stream2, stream3]);
181+
mergedStream.listen(print);
182+
```
183+
184+
23. **StreamController?**
185+
Creates and manages a Stream:
186+
187+
```dart
188+
final controller = StreamController<int>();
189+
controller.add(1);
190+
controller.stream.listen(print);
191+
controller.close();
192+
```
193+
194+
24. **Lazy loading with Stream?**
195+
196+
```dart
197+
Stream<int> lazyNumbers() async* {
198+
for (int i = 1; i <= 5; i++) {
199+
await Future.delayed(Duration(seconds: 1));
200+
yield i;
201+
}
202+
}
203+
```
204+
205+
25. **StreamSubscription?**
206+
Represents a subscription to a Stream:
207+
208+
```dart
209+
final subscription = stream.listen(
210+
(data) => print('Data: $data'),
211+
onError: (error) => print('Error: $error'),
212+
onDone: () => print('Stream is done'),
213+
);
214+
```
215+
216+
26. **Creating a never-completing Future?**
217+
218+
```dart
219+
Future<void> neverComplete() => Completer<void>().future;
220+
```
221+
222+
27. **await for with streams?**
223+
Iterates over a Stream asynchronously:
224+
225+
```dart
226+
await for (final value in countStream(5)) {
227+
print(value);
228+
}
229+
```
230+
231+
28. **Completer for manual future completion?**
232+
233+
```dart
234+
Completer<String> completer = Completer<String>();
235+
Future<String> future = completer.future;
236+
completer.complete('Done');
237+
```
238+
239+
29. **Future.microtask?**
240+
Schedules a task in the microtask queue, higher priority than regular event queue:
241+
242+
```dart
243+
Future.microtask(() => print('Microtask'));
244+
```
245+
246+
30. **Stream.periodic?**
247+
Creates a periodic stream:
248+
249+
```dart
250+
Stream.periodic(Duration(seconds: 1), (i) => i).take(5).listen(print);
251+
```
252+
253+
31. **FutureOr type?**
254+
Represents a value that can be either a Future<T> or T:
255+
256+
```dart
257+
FutureOr<int> getValue(bool immediate) {
258+
return immediate ? 42 : Future.value(42);
259+
}
260+
```
261+
262+
32. **Async/await with providers?**
263+
264+
```dart
265+
class DataProvider extends ChangeNotifier {
266+
Future<void> fetchData() async {
267+
// Fetch data
268+
notifyListeners();
269+
}
270+
}
271+
```
272+
273+
33. **Async programming benefits?**
274+
Improves app responsiveness by allowing non-blocking execution of time-consuming operations.
275+
276+
34. **Error handling in async functions?**
277+
278+
```dart
279+
try {
280+
await fetchData();
281+
} catch (e) {
282+
print('Error: $e');
283+
}
284+
```
285+
286+
35. **Zone in Dart?**
287+
Provides a way to persist context across async operations and handle uncaught errors.
288+
289+
36. **Custom stream with StreamTransformer?**
290+
291+
```dart
292+
Stream<String> transformNumbers(Stream<int> stream) {
293+
return stream.transform(StreamTransformer<int, String>.fromHandlers(
294+
handleData: (int data, EventSink<String> sink) {
295+
sink.add('Number: $data');
296+
},
297+
));
298+
}
299+
```
300+
301+
37. **Stream.listen?**
302+
Subscribes to a stream and handles its events:
303+
304+
```dart
305+
stream.listen(
306+
(data) => print('Received: $data'),
307+
onError: (error) => print('Error: $error'),
308+
onDone: () => print('Stream is done'),
309+
);
310+
```
311+
312+
38. **Handling event streams in Flutter?**
313+
Use StreamBuilder or StreamProvider to rebuild UI based on stream events.
314+
315+
39. **StreamBuilder's initialData?**
316+
Provides an initial value before the stream emits its first event:
317+
318+
```dart
319+
StreamBuilder<int>(
320+
stream: countStream,
321+
initialData: 0,
322+
builder: (context, snapshot) => Text('Count: ${snapshot.data}'),
323+
)
324+
```
325+
326+
40. **Converting Stream to Future?**
327+
328+
```dart
329+
Future<List<int>> streamToFuture(Stream<int> stream) => stream.toList();
330+
```
331+
332+
41. **async keyword usage?**
333+
Used to define asynchronous functions that contain await expressions or return a Future.
334+
335+
42. **Countdown timer with Future?**
336+
337+
```dart
338+
Future<void> countdown(int seconds) async {
339+
for (int i = seconds; i > 0; i--) {
340+
print(i);
341+
await Future.delayed(Duration(seconds: 1));
342+
}
343+
}
344+
```
345+
346+
43. **StreamController's add method?**
347+
Adds events to a stream controlled by a StreamController:
348+
349+
```dart
350+
final controller = StreamController<int>();
351+
controller.add(1);
352+
```
353+
354+
44. **Stream emitting values based on user input?**
355+
356+
```dart
357+
final controller = StreamController<String>();
358+
TextField(onChanged: controller.add);
359+
controller.stream.listen(print);
360+
```
361+
362+
45. **StreamTransformer in data manipulation?**
363+
Used to modify, filter, or transform stream events.
364+
365+
46. **Combining multiple futures?**
366+
367+
```dart
368+
final results = await Future.wait([fetchUser(), fetchPosts(), fetchComments()]);
369+
```
370+
371+
47. **Stream.where for filtering?**
372+
373+
```dart
374+
final evenNumbers = numberStream.where((number) => number % 2 == 0);
375+
```
376+
377+
48. **Progress indicator for async tasks?**
378+
Use StreamBuilder with a progress stream to update a LinearProgressIndicator.
379+
380+
49. **Async vs synchronous programming?**
381+
Async allows concurrent operations without blocking, sync executes sequentially and blocks until each operation completes.
382+
383+
50. **Background tasks in Flutter?**
384+
Use packages like workmanager or flutter_background_service to schedule and execute background tasks, even when the app is not in the foreground.

0 commit comments

Comments
 (0)