0% found this document useful (0 votes)
6 views

Lab 07

Mobile Application Development in flutter Lab Manual for NUST NBC

Uploaded by

Bakht Khilji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lab 07

Mobile Application Development in flutter Lab Manual for NUST NBC

Uploaded by

Bakht Khilji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Lab # 07

Mobile Application Development


Fall 2022

Instructor Bakht Muhammad

Student Name

CMSID

Department Computer Science

Semester 5th
Lesson Set Building Flutter Applications with
Asynchronous Functionality
7
Purpose 1. Understand the importance of asynchronous programming in Flutter.
2. Learn how to work with Future, async, and await in Flutter.
3. Build a Flutter application that fetches data asynchronously from an API or a
local database.

Procedure 4. Students should read the Pre-lab Reading assignment before coming to the
lab.
5. Students should complete the Pre-lab Writing assignment before entering
the lab.
6. In the lab, students should complete Labs 7.1 through 7.4 in sequence.
Your instructor will give further instructions on grading and completing the
lab.
7. Students should complete the set of lab tasks before the next lab and get
them checked by their lab instructor.

Contents Pre-requisites Completion Page


Time Number

Pre-lab Reading Assignment - 20 min 3

Pre-lab Writing Assignment Pre-lab Reading 10 min 7

Lab 7

Lab 7.1 Pre-lab reading 30 min 4


Future, async and await

Lab 7.2 Awareness of - 8


Lab Tasks Programming

2|Page
PRE-LAB READING ASSIGNMENT

Asynchronous What is Asynchronous Programming?


Programming
Synchronous Programming: Executes tasks sequentially, meaning one task
must finish before the next begins. This can block the user interface (UI) if a
task, like fetching data from a server, takes a long time.

Asynchronous Programming: Allows tasks to run in the background while


the main program continues executing. Ensures that long-running tasks like
network requests, file operations, or animations do not freeze the UI.

Key Concepts in Flutter Asynchronous Programming

Future: A Future is an object that represents the result of an asynchronous


operation. It can have one of two states:
1. Pending (operation still in progress).
2. Completed (operation has finished, successfully or with an error).
Future<String> fetchData() async {
return "Data fetched successfully!";
}

async and await


 async: Marks a function as asynchronous, allowing the use of await
inside it.
 await: Pauses the execution of a function until the awaited Future
completes.
Future<void> fetchAndPrintData() async {
print("Fetching data...");
await Future.delayed(Duration(seconds: 2)); // Simulating a delay
print("Data fetched!");

3|Page
}

Stream: A Stream is a sequence of asynchronous events. It is used when


you expect multiple data values over time. Commonly used for real-time data
updates like live chats or stock price changes.
Stream<int> countStream() async* {
for (int i = 1; i <= 5; i++) {
await Future.delayed(Duration(seconds: 1));
yield i; // Emits values one by one
}}

Handling Asynchronous Data in Flutter

Fetching Data from APIs: Flutter apps often fetch data from web APIs using
libraries like http or dio. The http package provides a simple way to send
GET, POST, and other requests.

import 'package:http/http.dart' as http;


import 'dart:convert';

Future<void> fetchApiData() async {


final response = await
http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts/1"));
if (response.statusCode == 200) {
final data = json.decode(response.body);
print(data['title']);
} else {
print("Failed to fetch data");
}}

Simulating Delayed Operations


 Delays are often used for testing or simulating slow processes.
 The Future.delayed() method can simulate delayed tasks.

Future<void> simulateDelay() async {


print("Starting task...");
await Future.delayed(Duration(seconds: 3));
print("Task completed after delay!");
}

Error Handling in Async Functions


Use try-catch blocks to handle errors in asynchronous operations gracefully.

Future<void> fetchWithErrorHandling() async {

4|Page
try {
await Future.delayed(Duration(seconds: 2));
throw Exception("An error occurred during the operation");
} catch (e) {
print("Error: $e");
}}

Asynchronous Widgets in Flutter

FutureBuilder: A widget that builds itself based on the latest snapshot of


interaction with a Future. Commonly used for fetching data asynchronously
and updating the UI.

Future<String> fetchData() async {


await Future.delayed(Duration(seconds: 2));
return "Data fetched!";
}

Widget build(BuildContext context) {


return FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator(); // Show a loading spinner
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error}");
} else {
return Text("Result: ${snapshot.data}");
} }, ); }

StreamBuilder: Similar to FutureBuilder, but works with Stream instead of


Future. Updates the UI each time the stream emits a new value.

Stream<int> numberStream() async* {


for (int i = 1; i <= 10; i++) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: numberStream(),

5|Page
builder: (context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return Text("Number: ${snapshot.data}");
},); }

Aspect FutureBuilder StreamBuilder


Input Type Single Future Continuous Stream
Use Case Fetching one-time data (e.g., Real-time updates (e.g., live
API calls). scores).
Update Only once (when Future Continuously as Stream emits
Frequency completes). new values.

Practical Applications of Asynchronous Programming


 Fetching API Data: Fetching data from REST APIs for apps like
weather, news, or e-commerce.
 Database Operations: Reading or writing data to databases like
Firebase Firestore or SQLite.
 Real-time Updates: Streaming live data, such as in a chat app or stock
ticker.
 Background Tasks: Running tasks like sending notifications or syncing
data in the background.

Key 1. Use Future to represent one-time asynchronous operations.


Takeaways 2. Use async and await for clean and easy-to-read asynchronous code.
3. Handle errors with try-catch blocks to avoid app crashes.
4. Utilize FutureBuilder and StreamBuilder for integrating asynchronous
data with Flutter UI.
5. Test all asynchronous code thoroughly to ensure responsiveness and
reliability.

6|Page
PRELAB WRITING ASSIGNMENT

Fill in the 1. A ______ in Flutter is used to represent the result of an asynchronous


blanks operation, which may be completed or still in progress.

2. The keyword ______ is used to mark a function as asynchronous in Dart,


allowing the use of the await keyword within it.

3. The ______ widget in Flutter is commonly used to build a UI based on the


result of a Future or an asynchronous operation.

4. To handle real-time data in Flutter, you can use a ______, which emits a
sequence of asynchronous events over time.

5. The ______ widget in Flutter listens to a Stream and rebuilds the UI every
time the stream emits a new value.

7|Page
Lab 7.2 Lab Tasks

Task 1: Create a Timer App


 Build a Flutter app where a button starts a timer.
 Display the countdown time on the screen.
 Use Future.delayed() to handle the timer.

 Screenshot should be pasted here.


 GitHub Repository link.

Task 2: Fetch Data from an API


 Use the http package to fetch a random post from JSONPlaceholder.
 Display the fetched data on the screen.
 Handle loading states with a loading spinner.

 Screenshot should be pasted here.


 GitHub Repository link.

Task 3: Async Database Query (Optional)


 Simulate fetching data from a local database using Future.delayed.
 Display the data in a list after a delay.

 Screenshot should be pasted here.


 GitHub Repository link.

Note: Make sure to upload the code for each task to a GitHub repository. Do not update or
change the repository after the due date. Provide the link to your GitHub repository with each
task submission.

8|Page

You might also like