Week 3 - Asynchronous Programming and Iterables
Week 3 - Asynchronous Programming and Iterables
FOR SMES
WEEK 3
OBJECTIVES
Asynchronous Programming
Iterable collection
ASYNCHRONOUS PROGRAMMING
WHY ASYNCHRONOUS CODE MATTERS
Asynchronous operations let your program complete work while waiting for another
operation to finish. There are some common asynchronous operations which are :
• Fetching data over a network.
• Writing to a database.
• Reading data from a file.
WHY ASYNCHRONOUS CODE MATTERS
A future (lower case "f") is an instance of the Future (capitalized "F") class.
A future represents the result of an asynchronous operation and can have two states:
Uncompleted
Uncompleted is a Dart term referring to the state of a future before it has produced a value.
Completed
If the asynchronous operation succeeds, the future completes with a value. Otherwise, it completes with an
error.
COMPLETED
Output
Thunderbird
FUTURE
The async and await keywords provide a declarative way to define asynchronous
functions and use their results.
Remember these two basic guidelines when using async and await:
To define an async function, add async before the function body:
The await keyword works only in async functions.
If the function has a declared return type, then update the type to be Future<T>, where T
is the type of the value that the function returns. If the function doesn't explicitly return a
value, then the return type is Future<void>:
print(await createOrderMessage());
EXAMPLE
void main() {
print('Before calling doSomethingAsync');
doSomethingAsync();
print('Main');
}
THEN KEYWORD
Basic Syntax
futureObject.then((result) {
// do something with the result of the future
}).catchError((error) {
// handle any errors that occur while processing the future
});
EXAMPLE
void main() {
addNumbers(2, 3).then((result) {
print('The result is: $result');
}).catchError((error) {
print('An error occurred: $error');
});
}
EXAMPLE
void main() {
addNumbers(2, 3).then((result) {
print('The result is: $result');
}).catchError((error) {
print('An error occurred: $error');
});
print("Hello");
}
TASK – PREDICT THE OUTPUT OF BOTH
String createOrderMessage() { Example: asynchronous functions #
var order = fetchUserOrder(); Future<String> createOrderMessage() async {
A collection is an object that represents a group of objects, which are called elements.
Iterables are a kind of collection.
A collection can be empty, or it can contain many elements.
Depending on the purpose, collections can have different structures and implementations.
These are some of the most common collection types:
List: Used to read elements by their indexes.
Set: Used to contain elements that can occur only once.
Map: Used to read elements using a key.
WHAT IS AN ITERABLE?
If you read elements with [], the compiler tells you that the operator '[]' isn't defined for
the class Iterable, which means that you can't use [index] in this case.
You can instead read elements with elementAt(), which steps through the elements of the
iterable until it reaches that position.
Iterable<int> iterable = [1, 2, 3];
int value = iterable.elementAt(1);
READING ELEMENTS
void main() {
const iterable = ['Salad', 'Popcorn', 'Toast'];
for (final element in iterable) {
print(element);
}
}
ACCESSING ELEMENTS
void main() {
In some cases, you want to access only Iterable<String> iterable = const
the first or the last element of an ['Salad', 'Popcorn', 'Toast'];
print('The first element is $
Iterable.
{iterable.first}');
With the Iterable class, you can't access print('The last element is $
the elements directly, so you can't call {iterable.last}');
iterable[0] to access the first element. }
Instead, you can use first, which gets the
first element.
Also, with the Iterable class, you can't
use the operator [] to access the last
element, but you can use the last
property.
FINDING ELEMENTS
void main() {
const items = ['Salad', 'Popcorn', 'Toast'];
The Iterable class provides
two methods that you can if (items.any((item) => item.contains('a'))) {
use to verify conditions: print('At least one item contains "a"');
any(): Returns true if at least }
one element satisfies the
condition. if (items.every((item) => item.length >= 5)) {
every(): Returns true if all print('All items have length >= 5');
elements satisfy the }
condition. }
FILTERING ELEMENTS
Mapping Iterables with the method map() enables you to apply a function over each of the
elements, replacing each element with a new one.
Iterable<int> output = numbers.map((number) => number * 10);
In this example, each element of the Iterable numbers is multiplied by 10.
You can also use map() to transform an element into a different object—for example, to
convert all int to String, as you can see in the following example:
Iterable<String> output = numbers.map((number) => number.toString());
ANY QUESTIONS?