SlideShare a Scribd company logo
Mobile Application Development
class 08
Dr. Mazin Alkathiri
IT Department
Seiyun University
2023-2024
Using await async in Dart
• The async and await approaches in Dart are very similar to
other languages, which makes it a comfortable topic to grasp
for those who have used this pattern before. However, even if
you don’t have experience with asynchronous programming
using async/await, you should find it easy to learn in dart.
Why asynchronous code matters
Asynchronous operations let your program complete work
while waiting for another operation to finish. Here are some common
asynchronous operations:
• Fetching data over a network.
• Writing to a database.
• Reading data from a file.
Such asynchronous computations usually provide their result as
a Future or, if the result has multiple parts, as a Stream. These
computations introduce asynchrony into a program. To accommodate
that initial asynchrony, other plain Dart functions also need to
become asynchronous.
• To interact with these asynchronous results, you can use the
async and await keywords. Most asynchronous functions are
just async Dart functions that depend, possibly deep down, on
an inherently asynchronous computation.
Example: Incorrectly using an asynchronous function
Here’s why the example fails to print the value that fetchUserOrder() eventually produces:
• fetchUserOrder() is an asynchronous function that, after a delay, provides a string that describes the
user’s order: a “Large Latte”.
• To get the user’s order, createOrderMessage() should call fetchUserOrder() and wait for it to finish.
Because createOrderMessage() does not wait for fetchUserOrder() to finish, createOrderMessage()
fails to get the string value that fetchUserOrder() eventually provides.
• Instead, createOrderMessage() gets a representation of pending work to be done: an uncompleted
future. You’ll learn more about futures in the next section.
• Because createOrderMessage() fails to get the value describing the user’s order, the example fails to
print “Large Latte” to the console, and instead prints “Your order is: Instance of ‘_Future<String>’”.
Key terms:
• synchronous operation: A synchronous operation blocks other operations from
executing until it completes.
• synchronous function: A synchronous function only performs synchronous operations.
• asynchronous operation: Once initiated, an asynchronous operation allows other
operations to execute before it completes.
• asynchronous function: An asynchronous function performs at least one asynchronous
operation and can also perform synchronous operations.
What is a future?
• 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 or completed.
• Uncompleted
– When you call an asynchronous function, it returns an uncompleted
future. That future is waiting for the function’s asynchronous operation to
finish or to throw an error.
• Completed
– If the asynchronous operation succeeds, the future completes with a
value. Otherwise, it completes with an error.
Completing with a value
• A future of type Future<T> completes with a value of type T.
For example, a future with type Future<String> produces a
string value. If a future doesn’t produce a usable value, then
the future’s type is Future<void>.
• Completing with an error
• If the asynchronous operation performed by the function fails
for any reason, the future completes with an error.
Example: Introducing futures
• In the following example, fetchUserOrder() returns a future that completes
after printing to the console. Because it doesn’t return a usable value,
fetchUserOrder() has the type Future<void>. Before you run the example,
try to predict which will print first: “Large Latte” or “Fetching user order…”.
Example: Completing with an error
• Run the following example to see how a future completes with an
error. A bit later you’ll learn how to handle the error.
• In this example, fetchUserOrder() completes with an error
indicating that the user ID is invalid.
Working with futures: async and await
• 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.
• Here’s an example that converts main() from a synchronous to
asynchronous function.
– First, add the async keyword before the function body:
• void main() async { ··· }
– 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>:
• Future<void> main() async { ··· }
– Now that you have an async function, you can use the await keyword to
wait for a future to complete:
• print(await createOrderMessage());
Future<String> createOrderMessage() async {
var order = await fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
// Imagine that this function is
// more complex and slow.
Future.delayed(
const Duration(seconds: 2),
() => 'Large Latte',
);
Future<void> main() async {
print('Fetching user order...');
print(await createOrderMessage());
}
String createOrderMessage() {
var order = fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
// Imagine that this function is
// more complex and slow.
Future.delayed(
const Duration(seconds: 2),
() => 'Large Latte',
);
void main() {
print('Fetching user order...');
print(createOrderMessage());
}
The asynchronous example is different in three ways:
• The return type for createOrderMessage() changes from String to Future<String>.
• The async keyword appears before the function bodies for createOrderMessage() and main().
• The await keyword appears before calling the asynchronous functions fetchUserOrder() and createOrderMessage().
Key terms:
• async: You can use the async keyword before a function’s body to mark it as
asynchronous.
• async function: An async function is a function labeled with the async
keyword.
• await: You can use the await keyword to get the completed result of an
asynchronous expression. The await keyword only works within an async
function.
• Execution flow with async and await
– An async function runs synchronously until the first await keyword. This means that
within an async function body, all synchronous code before the first await keyword
executes immediately.
Mobile Application Development class 008

More Related Content

PDF
Asynchronous Programming. Talk from ESUG2024
PDF
The Talk You've Been Await-ing For
PDF
The Evolution of Asynchronous Javascript - Alessandro Cinelli - Codemotion Mi...
PPTX
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
PPTX
Javascript async / await Frontend-IL
PPTX
Async discussion 9_29_15
PDF
The evolution of asynchronous javascript
PDF
Intro to Asynchronous Javascript
Asynchronous Programming. Talk from ESUG2024
The Talk You've Been Await-ing For
The Evolution of Asynchronous Javascript - Alessandro Cinelli - Codemotion Mi...
asyncjavascript.pptxdgdsgdffgfdgfgfgfdgfdgf
Javascript async / await Frontend-IL
Async discussion 9_29_15
The evolution of asynchronous javascript
Intro to Asynchronous Javascript

Similar to Mobile Application Development class 008 (20)

PPTX
Async all around us (promises)
PDF
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
PDF
Async Await for Mobile Apps
PDF
Introducing Async/Await
PDF
How to Handle Asynchronous Operations in Flutter Applications.pdf
PDF
Asynchronous development in JavaScript
PPTX
C++11 Multithreading - Futures
PPTX
Ecma script
PPTX
Async ... Await – concurrency in java script
PDF
The evolution of asynchronous JavaScript
PPTX
Async e await com JavaScript: entenda e use agora
PPTX
advance-dart.pptx
PPT
You promise?
PDF
How to stop debugging asynchronous code and start living, Andrey Salomatin, B...
PPTX
An introduction to Object Oriented JavaScript
PPTX
Promise of a better future by Rahul Goma Phulore and Pooja Akshantal, Thought...
KEY
Asynchronous Programming
PDF
From Node.js to Design Patterns - BuildPiper
PDF
JavaScript Promises Simplified [Free Meetup]
PDF
JavaScript Editions ES7, ES8 and ES9 vs V8
Async all around us (promises)
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
Async Await for Mobile Apps
Introducing Async/Await
How to Handle Asynchronous Operations in Flutter Applications.pdf
Asynchronous development in JavaScript
C++11 Multithreading - Futures
Ecma script
Async ... Await – concurrency in java script
The evolution of asynchronous JavaScript
Async e await com JavaScript: entenda e use agora
advance-dart.pptx
You promise?
How to stop debugging asynchronous code and start living, Andrey Salomatin, B...
An introduction to Object Oriented JavaScript
Promise of a better future by Rahul Goma Phulore and Pooja Akshantal, Thought...
Asynchronous Programming
From Node.js to Design Patterns - BuildPiper
JavaScript Promises Simplified [Free Meetup]
JavaScript Editions ES7, ES8 and ES9 vs V8
Ad

More from Dr. Mazin Mohamed alkathiri (20)

PPTX
Computer Introduction (Operating Systems)-Lecture06
PPTX
Mobile Application Development (local database) class-07
PPTX
Mobile Application Development (Shared Preferences) class-06
PPTX
Mobile Application Development((Handling User Input and Navigation) class-05
PPTX
Computer Introduction (Data Encryption)-Lecture05
PPTX
Computer Introduction (Computer Viruses )-Lecture04
PPTX
Mobile Applications Development class 04-Layout-04
DOCX
Appendix to Lecture 3 Building a flutter app
PPTX
Mobile Applications Development class 03-starting with flutter
PPTX
Mobile Applications Development class 02 ntroduction to Drat
PPTX
Computer Introduction (Software)-Lecture03
PPTX
Computer Introduction (Hardware)-Lecture02
PPTX
Computer Introduction (introduction)-Lecture01
PPTX
Introduction to Academic Writing class 0-1
PPTX
Mobile Applications Development class 01 - Introduction
PPT
OS-operating systems- ch05 (CPU Scheduling) ...
PPTX
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
PPTX
Advance Mobile Application Development class 07
PPTX
ESSENTIAL of (CS/IT/IS) class 06 (database)
PPT
OS-operating systems- ch04 (Threads) ...
Computer Introduction (Operating Systems)-Lecture06
Mobile Application Development (local database) class-07
Mobile Application Development (Shared Preferences) class-06
Mobile Application Development((Handling User Input and Navigation) class-05
Computer Introduction (Data Encryption)-Lecture05
Computer Introduction (Computer Viruses )-Lecture04
Mobile Applications Development class 04-Layout-04
Appendix to Lecture 3 Building a flutter app
Mobile Applications Development class 03-starting with flutter
Mobile Applications Development class 02 ntroduction to Drat
Computer Introduction (Software)-Lecture03
Computer Introduction (Hardware)-Lecture02
Computer Introduction (introduction)-Lecture01
Introduction to Academic Writing class 0-1
Mobile Applications Development class 01 - Introduction
OS-operating systems- ch05 (CPU Scheduling) ...
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
Advance Mobile Application Development class 07
ESSENTIAL of (CS/IT/IS) class 06 (database)
OS-operating systems- ch04 (Threads) ...
Ad

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Institutional Correction lecture only . . .
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Lesson notes of climatology university.
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Basic Mud Logging Guide for educational purpose
Final Presentation General Medicine 03-08-2024.pptx
Sports Quiz easy sports quiz sports quiz
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
RMMM.pdf make it easy to upload and study
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
VCE English Exam - Section C Student Revision Booklet
Institutional Correction lecture only . . .
PPH.pptx obstetrics and gynecology in nursing
Insiders guide to clinical Medicine.pdf
Microbial diseases, their pathogenesis and prophylaxis
Lesson notes of climatology university.
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf

Mobile Application Development class 008

  • 1. Mobile Application Development class 08 Dr. Mazin Alkathiri IT Department Seiyun University 2023-2024
  • 2. Using await async in Dart • The async and await approaches in Dart are very similar to other languages, which makes it a comfortable topic to grasp for those who have used this pattern before. However, even if you don’t have experience with asynchronous programming using async/await, you should find it easy to learn in dart.
  • 3. Why asynchronous code matters Asynchronous operations let your program complete work while waiting for another operation to finish. Here are some common asynchronous operations: • Fetching data over a network. • Writing to a database. • Reading data from a file. Such asynchronous computations usually provide their result as a Future or, if the result has multiple parts, as a Stream. These computations introduce asynchrony into a program. To accommodate that initial asynchrony, other plain Dart functions also need to become asynchronous.
  • 4. • To interact with these asynchronous results, you can use the async and await keywords. Most asynchronous functions are just async Dart functions that depend, possibly deep down, on an inherently asynchronous computation.
  • 5. Example: Incorrectly using an asynchronous function
  • 6. Here’s why the example fails to print the value that fetchUserOrder() eventually produces: • fetchUserOrder() is an asynchronous function that, after a delay, provides a string that describes the user’s order: a “Large Latte”. • To get the user’s order, createOrderMessage() should call fetchUserOrder() and wait for it to finish. Because createOrderMessage() does not wait for fetchUserOrder() to finish, createOrderMessage() fails to get the string value that fetchUserOrder() eventually provides. • Instead, createOrderMessage() gets a representation of pending work to be done: an uncompleted future. You’ll learn more about futures in the next section. • Because createOrderMessage() fails to get the value describing the user’s order, the example fails to print “Large Latte” to the console, and instead prints “Your order is: Instance of ‘_Future<String>’”.
  • 7. Key terms: • synchronous operation: A synchronous operation blocks other operations from executing until it completes. • synchronous function: A synchronous function only performs synchronous operations. • asynchronous operation: Once initiated, an asynchronous operation allows other operations to execute before it completes. • asynchronous function: An asynchronous function performs at least one asynchronous operation and can also perform synchronous operations.
  • 8. What is a future? • 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 or completed. • Uncompleted – When you call an asynchronous function, it returns an uncompleted future. That future is waiting for the function’s asynchronous operation to finish or to throw an error. • Completed – If the asynchronous operation succeeds, the future completes with a value. Otherwise, it completes with an error.
  • 9. Completing with a value • A future of type Future<T> completes with a value of type T. For example, a future with type Future<String> produces a string value. If a future doesn’t produce a usable value, then the future’s type is Future<void>. • Completing with an error • If the asynchronous operation performed by the function fails for any reason, the future completes with an error.
  • 10. Example: Introducing futures • In the following example, fetchUserOrder() returns a future that completes after printing to the console. Because it doesn’t return a usable value, fetchUserOrder() has the type Future<void>. Before you run the example, try to predict which will print first: “Large Latte” or “Fetching user order…”.
  • 11. Example: Completing with an error • Run the following example to see how a future completes with an error. A bit later you’ll learn how to handle the error. • In this example, fetchUserOrder() completes with an error indicating that the user ID is invalid.
  • 12. Working with futures: async and await • 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.
  • 13. • Here’s an example that converts main() from a synchronous to asynchronous function. – First, add the async keyword before the function body: • void main() async { ··· } – 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>: • Future<void> main() async { ··· } – Now that you have an async function, you can use the await keyword to wait for a future to complete: • print(await createOrderMessage());
  • 14. Future<String> createOrderMessage() async { var order = await fetchUserOrder(); return 'Your order is: $order'; } Future<String> fetchUserOrder() => // Imagine that this function is // more complex and slow. Future.delayed( const Duration(seconds: 2), () => 'Large Latte', ); Future<void> main() async { print('Fetching user order...'); print(await createOrderMessage()); } String createOrderMessage() { var order = fetchUserOrder(); return 'Your order is: $order'; } Future<String> fetchUserOrder() => // Imagine that this function is // more complex and slow. Future.delayed( const Duration(seconds: 2), () => 'Large Latte', ); void main() { print('Fetching user order...'); print(createOrderMessage()); } The asynchronous example is different in three ways: • The return type for createOrderMessage() changes from String to Future<String>. • The async keyword appears before the function bodies for createOrderMessage() and main(). • The await keyword appears before calling the asynchronous functions fetchUserOrder() and createOrderMessage().
  • 15. Key terms: • async: You can use the async keyword before a function’s body to mark it as asynchronous. • async function: An async function is a function labeled with the async keyword. • await: You can use the await keyword to get the completed result of an asynchronous expression. The await keyword only works within an async function. • Execution flow with async and await – An async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.