Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

MAD-Lab-03- [Generics, Asynchronous Programming & Iterable

collections]

Instructor: Dr. Hasan Ali Khattak & Dr. Yasir Faheem

Lab Engineer: Mr. Aftab Farooq

Name: Muhammad Umer Farooq


Class: BESE 9A
CMS ID: 266086

Task 1:

Future<String> reportUserRole() async {


var username = await fetchRole();
return 'User role: $username';

Future<String> reportLogins() async {


var logins = await fetchLoginAmount();
return 'Total number of logins: $logins';
}

Output:
Future<String> changeUsername () async {
try {
return await fetchNewUsername();
} catch (err) {
return err.toString();
}
}

String addHello(user) => 'Hello $user';

Future<String> greetUser() async {


var username = await fetchUsername();
return addHello(username);
}
Future<String> sayGoodbye() async {
try {
var result = await logoutUser();
return '$result Thanks, see you next time';
} catch (e) {
return 'Failed to logout user: $e';
}
}

Task 2:

Part 1:

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

class SearchResult {
// TODO: add properties and constructors to initialise your model
class
String content_type;
String title;
List<String> tags;
String pubDate;
String url;

SearchResult(
this.content_type, this.title, this.tags, this.pubDate,
this.url);

@override
String toString() {
// TODO: implement toString
return "Search Result => 'ContentType' : ${content_type}
'title' : ${title} 'tags' : ${tags} 'PubDate': ${pubDate} 'url' : $
{url}";
}
}

class APIClient {
Future<List<SearchResult>> downloadAndParseJson() async {
const uriString =
'https://codewithandrea.com/search/search.json';
final response = await http.get(Uri.parse(uriString));
if (response.statusCode == 200) {
final parser = SearchResultsParser(response.body);
return parser.parseInBackground();
} else {
throw Exception('Failed to load json');
}
}
}

class SearchResultsParser {
SearchResultsParser(this.encodedJson);
final String encodedJson;
Future<List<SearchResult>> parseInBackground() async {
final p = ReceivePort();
await Isolate.spawn(_decodeAndParseJson, p.sendPort);

return await p.first;


}

Future<void> _decodeAndParseJson(SendPort p) async {


final jsonData = jsonDecode(encodedJson);
final resultsJson = jsonData['results'];
List<SearchResult> my_res = [];
for (final res in resultsJson) {
List<String> tag_parsed = [];
for (final tag in res['tags']) {
String test = tag as String;
tag_parsed.add(test);
}
my_res.add(SearchResult(res['contentType'], res['title'],
tag_parsed,
res['date'], res['url']));
}
Isolate.exit(p, my_res);
}
}

void main() async {


APIClient new_cl = APIClient();
List<SearchResult> res = await new_cl.downloadAndParseJson();
for (final results in res) {
print(results);
}
}

Output:

Part 2:

import 'dart:convert';
import 'dart:isolate';
import 'package:http/http.dart' as http;
class SearchResult {
// TODO: add properties and constructors to initialise your model
class
String content_type;
String title;
List<String> tags;
String pubDate;
String url;

SearchResult(
this.content_type, this.title, this.tags, this.pubDate,
this.url);

@override
String toString() {
// TODO: implement toString
return "Search Result => 'ContentType' : ${content_type}
'title' : ${title} 'tags' : ${tags} 'PubDate': ${pubDate} 'url' : $
{url}";
}
}

class SearchResultCustom {
// TODO: add properties and constructors to initialise your model
class
int albumId;
int id;
String title;
String thumbnailUrl;
String url;

SearchResultCustom(
this.albumId, this.title, this.thumbnailUrl, this.id,
this.url);

@override
String toString() {
// TODO: implement toString
return "Search Result => 'Album Id' : ${albumId} 'ID' : ${id}
'Thumbnail URL' : ${thumbnailUrl} 'ID': ${id} 'url' : ${url}";
}
}
class APIClient {
Future<List<dynamic>> downloadAndParseJson(var url) async {
var uriString = url;
final response = await http.get(Uri.parse(uriString));
if (response.statusCode == 200) {
final parser = SearchResultsParser(response.body);
return parser.parseInBackground();
} else {
throw Exception('Failed to load json');
}
}
}

class SearchResultsParser {
SearchResultsParser(this.encodedJson);
final String encodedJson;
Future<List<dynamic>> parseInBackground() async {
final p = ReceivePort();
await Isolate.spawn(_decodeAndParseJson, p.sendPort);
return await p.first;
}

Future<void> _decodeAndParseJson(SendPort p) async {


// decode and parse the json
final jsonData = jsonDecode(encodedJson);
final results = [];
if (jsonData is Map) {
final resultsJson = jsonData['results'];
for (final res in resultsJson) {
List<String> tag_parsed = [];
for (final tag in res['tags']) {
String test = tag as String;
tag_parsed.add(test);
}
results.add(SearchResult(res['contentType'], res['title'],
tag_parsed,
res['date'], res['url']));
}
} else {
for (final res in jsonData) {
results.add(SearchResultCustom(res['albumId'], res['title'],
res['thumbnailUrl'], res['id'], res['url']));
}
}
Isolate.exit(p, results);
}
}

void main() async {


APIClient new_cl = APIClient();
String url = 'https://jsonplaceholder.typicode.com/photos';
List<dynamic> res = await new_cl.downloadAndParseJson(url);
for (final results in res) {
print(results);
}
}

Output:

Task 3:

class EmailAddress {
String _email;

EmailAddress(this._email);

String get getEmail => _email;

@override
String toString() {
return _email;
}
}

Iterable<EmailAddress> parseEmailAddress(
Iterable<String> listOfEmailAddresses) {
return listOfEmailAddresses.map((s_email) =>
EmailAddress(s_email));
}

bool isValidEmailAddressRegExp(String email) {


return RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-
9]+\.[a-zA-Z]+")
.hasMatch(email);
}

bool anyInvalidEmailAddress(Iterable<EmailAddress>
listOfEmailAddresses) {
if (listOfEmailAddresses
.any((item) => !isValidEmailAddressRegExp(item.getEmail))) {
return true;
} else {
return false;
}
}

Iterable<EmailAddress> validEmailAddresses(
Iterable<EmailAddress> listOfEmailAddresses) {
return listOfEmailAddresses
.where((item) => isValidEmailAddressRegExp(item.getEmail));
}

void main() {
var mails = {"umer@gmail.com", "umer", "umer@",
"umer.farooq@gmail.com"};
Iterable<EmailAddress> addrs = parseEmailAddress(mails);
print("Iterable of string Emails: ${mails}");
print("Iterable of Email Addresses: ${addrs}");
print("Valid Email Addresses: ${validEmailAddresses(addrs)}");
print(
"Invalid Email Addresses:(check for existence) $
{anyInvalidEmailAddress(addrs)}");
}

output:

You might also like