SlideShare a Scribd company logo
1 of 16
Download to read offline
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

Similar to Mobile Application Development class 008

Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
gerrell
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
olracoatalub
 

Similar to Mobile Application Development class 008 (20)

Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
My final requirement
My final requirementMy final requirement
My final requirement
 
Macasu, gerrell c.
Macasu, gerrell c.Macasu, gerrell c.
Macasu, gerrell c.
 
Async Await for Mobile Apps
Async Await for Mobile AppsAsync Await for Mobile Apps
Async Await for Mobile Apps
 
Understanding Framework Architecture using Eclipse
Understanding Framework Architecture using EclipseUnderstanding Framework Architecture using Eclipse
Understanding Framework Architecture using Eclipse
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...Guidelines to understand durable functions with .net core, c# and stateful se...
Guidelines to understand durable functions with .net core, c# and stateful se...
 
Asynchronyin net
Asynchronyin netAsynchronyin net
Asynchronyin net
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
Basic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.jsBasic Understanding and Implement of Node.js
Basic Understanding and Implement of Node.js
 

More from Dr. Mazin Mohamed alkathiri

More from Dr. Mazin Mohamed alkathiri (20)

OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Advance Mobile Application Development class 05
Advance Mobile Application Development class 05Advance Mobile Application Development class 05
Advance Mobile Application Development class 05
 
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
ESSENTIAL of (CS/IT/IS) class 05 (Software concepts)
 
OS-operating systems- ch03
OS-operating systems- ch03OS-operating systems- ch03
OS-operating systems- ch03
 
OS-operating systems - ch02 - part-2-2024
OS-operating systems - ch02 - part-2-2024OS-operating systems - ch02 - part-2-2024
OS-operating systems - ch02 - part-2-2024
 
Advance Mobile Application Development class 04
Advance Mobile Application Development class 04Advance Mobile Application Development class 04
Advance Mobile Application Development class 04
 
Advance Mobile Application Development class 03
Advance Mobile Application Development class 03Advance Mobile Application Development class 03
Advance Mobile Application Development class 03
 
Advance Mobile Application Development class 02-B
Advance Mobile Application Development class 02-BAdvance Mobile Application Development class 02-B
Advance Mobile Application Development class 02-B
 
OS-ch02-part-1-2024.ppt
OS-ch02-part-1-2024.pptOS-ch02-part-1-2024.ppt
OS-ch02-part-1-2024.ppt
 
Advance Mobile Application Development class 02
Advance Mobile Application Development class 02Advance Mobile Application Development class 02
Advance Mobile Application Development class 02
 
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
ESSENTIAL of (CS/IT/IS) class 03-04 (NUMERIC SYSTEMS)
 
Advance Mobile Application Development class 01
Advance Mobile Application Development class 01Advance Mobile Application Development class 01
Advance Mobile Application Development class 01
 
ESSENTIAL of (CS/IT/IS) class 02 (HCI)
ESSENTIAL of (CS/IT/IS) class 02 (HCI)ESSENTIAL of (CS/IT/IS) class 02 (HCI)
ESSENTIAL of (CS/IT/IS) class 02 (HCI)
 
Seminar
SeminarSeminar
Seminar
 
ESSENTIAL of (CS/IT/IS)
ESSENTIAL of (CS/IT/IS)ESSENTIAL of (CS/IT/IS)
ESSENTIAL of (CS/IT/IS)
 
OS-ch01-2024.ppt
OS-ch01-2024.pptOS-ch01-2024.ppt
OS-ch01-2024.ppt
 

Recently uploaded

Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 

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.