0% found this document useful (0 votes)
12 views41 pages

W25 - BSCS-7 / BSSE-7: Dr. Tanzila Kehkashan

The document outlines a course on Mobile Application Development (MADT-4118) led by Dr. Tanzila Kehkashan, focusing on Flutter as a cross-platform development tool. It covers essential topics such as environment setup, Dart programming, and Flutter basics including UI components and widgets. The course emphasizes the benefits of Flutter, including faster time to market, cost efficiency, and a growing community, while providing a structured assessment and evaluation criteria.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views41 pages

W25 - BSCS-7 / BSSE-7: Dr. Tanzila Kehkashan

The document outlines a course on Mobile Application Development (MADT-4118) led by Dr. Tanzila Kehkashan, focusing on Flutter as a cross-platform development tool. It covers essential topics such as environment setup, Dart programming, and Flutter basics including UI components and widgets. The course emphasizes the benefits of Flutter, including faster time to market, cost efficiency, and a growing community, while providing a structured assessment and evaluation criteria.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Mobile Application Development

MADT-4118​

W25 - BSCS-7 / BSSE-7

Instructor
Dr. Tanzila Kehkashan


UOL-Sgd

1
Module 1: Introduction to Mobile Application Development.............................................................3
1.1. Assessment & Evaluation Criteria.................................................................................... 3
1.2. What is Flutter?.................................................................................................................3
Key Concept: Cross-Platform Development...................................................................... 3
Why is Cross-Platform Development Important?...............................................................3
1.1 Understanding Key Terms............................................................................................4
1.2 How is Flutter Different from Other Cross-Platform Tools?................................................5
Advantages of Flutter’s Rendering.......................................................................................... 5
1.4 Benefits of Flutter...............................................................................................................6
1.4.1 Faster Time to Market............................................................................................... 6
1.4.2 Cost Efficiency.......................................................................................................... 6
1.4.3. High Performance.................................................................................................... 6
1.4.4. Customizable and Beautiful UI.................................................................................6
1.4.5. Growing Community and Ecosystem.......................................................................6
Module 2: Environment Setup.................................................................................................... 8
Module 3: Dart Programming Essentials.................................................................................10
3.1. What is Dart Programming............................................................................................. 10
3.2. Dart First Program.......................................................................................................... 14
3.3. Common Data Types in Dart.......................................................................................... 16
3.4 Declaration and Initialization............................................................................................16
3.5. Nullable and Non-Nullable Variables.............................................................................. 17
3.6 Variable Scope and Lifetime............................................................................................ 17
3.7. Mutable and Immutable Variables.................................................................................. 17
3.8. Dynamic and Var Keywords............................................................................................18
3.9. Conditional Operators in Dart......................................................................................... 18
3.10. If Condition....................................................................................................................19
3.11. Logical Operators in Dart.............................................................................................. 19
3.12. Ternary Operator (? :)................................................................................................... 19
3.13. Functions in Dart...........................................................................................................20
3.14. Lists in Dart...................................................................................................................24
3.15. Maps in Dart................................................................................................................. 28
3.16. OOP in Dart.................................................................................................................. 32
Module 4: Flutter Basics - UI Components & Widgets...........................................................39
4.1. Flutter Widgets Overview................................................................................................39
4.2. Text, Buttons, and Image Widgets.................................................................................. 39
4.3. Layouts: Rows, Columns & Stack...................................................................................39
4.4. Navigation & Routing in Flutter....................................................................................... 39
4.5. User Input Handling & Forms......................................................................................... 39

Instructor: Dr. Tanzila Kehkashan 2


4.6. State Management Overview (Stateless vs Stateful Widgets)....................................... 40

Instructor: Dr. Tanzila Kehkashan 3


Module 1: Introduction to Mobile Application
Development

1.1.​ Assessment & Evaluation Criteria


Mid Term​ ​ ​ 20 %

Final Term​ ​ ​ 40 %

Assignments​ ​ ​ 10 %

Quizzes​ ​ ​ 10 %

Semester Project​ ​ 20 %

Total:​ ​ ​ 100 %

1.2.​ What is Flutter?


Flutter is an open-source toolkit developed by Google that enables developers to build
natively compiled applications for multiple platforms using a single codebase.

Key Concept: Cross-Platform Development

Flutter is a cross-platform development tool. This means:

●​ You write one codebase.


●​ The same code runs on multiple platforms like Android, iOS, Web browsers, Desktop
(Windows, macOS, Linux)

Instead of writing separate codes for each platform, Flutter helps you save time and effort by
allowing you to reuse your code across different environments.

Why is Cross-Platform Development Important?

Real-world example: Imagine if you're building an app or software product, the goal is to reach
as many users as possible. In today's world, people use:

●​ Desktops/Laptops
●​ Mobile phones (Android & iOS)

Instructor: Dr. Tanzila Kehkashan 4


●​ Web browsers

To maximize your audience, your app needs to be available on all these platforms.

Traditional Approach: Normally, to support these platforms, developers must learn and work with
different languages and tools:

●​ Android: Java or Kotlin


●​ iOS: Swift or Objective-C
●​ Web: HTML, CSS, JavaScript
●​ Desktop: Java, C, C++

This requires different teams, different codebases, and a lot more time.

Cross-Platform with Flutter: Flutter solves this problem by allowing you to write one codebase
that works across all major platforms.

This helps you:

●​ Save time
●​ Reduce development costs
●​ Maintain only one codebase
●​ Ensure a consistent user experience

1.1 Understanding Key Terms

Native Development: Developing apps using the platform’s official languages and tools.

Example:

●​ Android apps → Java/Kotlin with Android Studio


●​ iOS apps → Swift/Objective-C with Xcode

- Native development means apps are optimized specifically for that platform, but require
separate codebases for each platform.

Hybrid Development: Hybrid apps combine web technologies (HTML, CSS, JS) inside a native
container to run as mobile apps.

- Common hybrid tools: Ionic, Apache Cordova, Capacitor

- Hybrid apps often feel like websites packaged into apps, and can sometimes suffer from
performance or native feature limitations.

Cross-Platform Development: Write your app’s code once and run it on multiple platforms.

Instructor: Dr. Tanzila Kehkashan 5


- Popular cross-platform tools: Flutter, React Native

- The goal is to balance native performance with code reuse across platforms.

1.2 How is Flutter Different from Other Cross-Platform Tools?


To understand Flutter's uniqueness, let’s compare how Flutter and other frameworks handle UI
rendering.

Example: Raised Button (a button with a shadow effect)

- In other cross-platform frameworks (like React Native):

- When running on iOS, the system uses the native UIButton component.

- On Android, it uses the native Widget.Button component.

- These frameworks rely on platform-specific components at runtime, increasing complexity and


potential inconsistencies.

- In Flutter:

- Flutter doesn’t rely on the platform's native components.

- It uses its own rendering engine called Skia.

- Flutter draws every pixel on the screen itself, making the UI fully customizable and consistent
across platforms.

Advantages of Flutter’s Rendering


- Pixel-perfect designs on any device.

- Consistent UI across platforms.

- No dependency on native UI components.

- Easier to implement complex and custom UIs.

1.3 Why Choose Flutter Over Other Cross-Platform Tools?

Flutter provides:

●​ Consistent performance across platforms.


●​ Beautiful and customizable UI.

Instructor: Dr. Tanzila Kehkashan 6


●​ Fewer platform limitations compared to hybrid solutions.
●​ Faster development through hot reload, which lets you see changes instantly.
●​ A single language (Dart) to learn for full app development.

1.4 Benefits of Flutter


1.4.1 Faster Time to Market

●​ - One codebase = less development time.


●​ - You can release apps to Android, iOS, web, and desktop simultaneously.
●​ - Ideal for startups and businesses looking to launch quickly.

1.4.2 Cost Efficiency

●​ No need to hire separate teams for each platform.


●​ Maintain one codebase, which reduces long-term costs.

1.4.3. High Performance

●​ Flutter compiles to native machine code.


●​ Smooth animations and transitions.
●​ Fast startup times.

1.4.4. Customizable and Beautiful UI

●​ Full control over every pixel.


●​ Easily create complex, beautiful, and responsive UIs.
●​ Consistent designs across all devices.

1.4.5. Growing Community and Ecosystem

●​ Backed by Google.
●​ Rich set of packages and plugins.
●​ Strong community support.

1.3.​ Flutter Architecture

1.4.​ Setting up Developer Accounts & Prerequisites


●​ Formal Definition:
○​ ML is a field of computer science that uses statistical techniques to enable
computers to learn from data without explicit programming.

Instructor: Dr. Tanzila Kehkashan 7


●​ Simplified Explanation:
○​ ML is about learning from data.
○​ Key term: "Explicit Programming":
■​ Traditional programming: Write code for each specific condition.
■​ ML: Provide data & algorithm → The model learns patterns from the data.
○​

Instructor: Dr. Tanzila Kehkashan 8


Module 2: Environment Setup

2.1. Installing Flutter on Windows

2.2. Setting up IDEs: Android Studio

2.3. Creating & Running a Flutter Project

Instructor: Dr. Tanzila Kehkashan 9


2.4. Git & GitHub Setup for Flutter Projects

Instructor: Dr. Tanzila Kehkashan

10
Module 3: Dart Programming Essentials

3.1. What is Dart Programming


Why Learn Dart Before Flutter?

●​ Flutter is a framework used for app development, but the programming language behind
it is Dart.
●​ Without understanding Dart, it would be difficult to develop apps in Flutter.
●​ Dart provides both UI development and backend logic in Flutter.
●​ Learning Dart first makes Flutter development easier and more efficient.
●​ Unlike Android or Web Development, Flutter uses only one language—Dart, making
development simpler and faster.

Comparison with Other Development Platforms

Platform Frontend Language Backend Language Database


(UI) (UX)

Instructor: Dr. Tanzila Kehkashan

11
Android XML Java/Kotlin SQLite, Firebase

Web Development HTML, CSS PHP, Codeigniter MySQL, Firebase

Flutter Dart (Single Language) Dart (Single Language) Firebase, SQLite

What is Dart?

●​ Dart is a front-end focused language used for UI development and logic building.
●​ It was developed by Google in 2011 to provide a better alternative to JavaScript.
●​ Dart is used for:
○​ Mobile application development (Flutter)
○​ Web development
○​ Desktop applications
●​ Developed by Google (2011)
●​ Object-Oriented Programming (OOP) Language
●​ Strongly Typed Language (Variables must have defined data types)
●​ Mixture of JavaScript, Java, and C#
●​ Can be compiled into JavaScript (for browser execution)
●​ Supports AOT (Ahead-of-Time) and JIT (Just-in-Time) Compilation
●​ Supports Asynchronous Programming (async, await)
●​ Supports Flutter’s Hot Reload & Hot Restart Features

Key Features of Dart

1. Strongly Typed & Object-Oriented Language

●​ Every variable in Dart has a defined type (e.g., int, String, double).
●​ Supports OOP concepts like classes, objects, inheritance, polymorphism, abstraction,
and encapsulation.

2. Asynchronous Programming (async, await)

●​ Helps handle time-consuming tasks like:


○​ Downloading files

Instructor: Dr. Tanzila Kehkashan

12
○​ Fetching data from a server
○​ Database calls
●​ Asynchronous programming = Parallel programming
●​ Dart provides async and await to handle asynchronous operations easily.

Example of async and await in Dart

void fetchData() async {

print("Fetching data...");

await Future.delayed(Duration(seconds: 3));

print("Data fetched successfully!");

Output:

Fetching data...

(Data fetched after 3 seconds)

Data fetched successfully!

3. Compilation in Dart (AOT vs JIT)

What is a Compiler?

●​ Converts human-written code into machine-readable instructions (bytecode).

Types of Compilation in Dart

Type Meaning Usage

JIT (Just-in-Time) Compiles code at runtime Used during development (Hot Reload,
Hot Restart)

Instructor: Dr. Tanzila Kehkashan

13
AOT Compiles code before Used for final app release
(Ahead-of-Time) execution

Benefits of AOT and JIT Compilation

●​ JIT:
○​ Hot Reload & Hot Restart allow fast UI changes.
○​ No need to restart the entire app after every small change.
●​ AOT:
○​ Optimizes performance for faster app startup.
○​ Used when compiling the final installable APK or iOS app.

Example of JIT (Hot Reload in Flutter)

Text("Hello World")

●​ If changed to "Hello Flutter" and hot reloaded, the UI updates instantly without
restarting the app.

4. Dart’s Role in Flutter Development

●​ Flutter provides pre-built widgets for UI development.


●​ Dart is used to write logic and define UI components.
●​ Everything in Flutter (UI & logic) is written in Dart (unlike Android where UI is XML and
logic is Java/Kotlin).

5. Dart Can Be Compiled into JavaScript

●​ This allows Dart to be used in web development.


●​ Flutter Web apps run because Dart is converted into JavaScript for browsers.

6. No Need for Separate UI Templating Language

●​ Unlike React Native (JSX) or Android (XML), Flutter uses Dart for UI & logic.
●​ This makes Flutter development faster and reduces the learning curve.

Instructor: Dr. Tanzila Kehkashan

14
3.2. Dart First Program

Creating a Dart File

To start programming in Dart:

1.​ Open Android Studio


2.​ Right-click on the lib folder → Click on New → Select Dart File
3.​ Give the file a meaningful name (e.g., practice.dart).
○​ Dart file names should use underscores (_) instead of spaces.

Understanding the Main Function

Every Dart program starts execution from the main function.

void main() {

runApp(MyApp());

Explanation:

●​ void → The return type (indicates that the function does not return any value).
●​ main() → The entry point of the program.
●​ print("Welcome to Dart"); → Prints a message to the console.

Basic Input and Output in Dart

Printing Output (Console Output)

To display messages in Dart, use print or stdout.write.

void main() {

print("Welcome to Dart"); // Using print()

Difference between print and stdout.write:

Instructor: Dr. Tanzila Kehkashan

15
●​ print() → Moves the cursor to the next line after displaying the message.
●​ stdout.write() → Keeps the cursor on the same line.

Taking User Input (Console Input)

To take user input, use stdin.readLineSync().

import 'dart:io';

void main() {

stdout.write("Enter your name: ");

String? name = stdin.readLineSync();

print("Welcome, $name!");

Explanation:

●​ import 'dart:io'; → Required for input/output operations.


●​ stdout.write("Enter your name: "); → Displays the message but does not
move to the next line.
●​ String? name = stdin.readLineSync(); → Reads input from the user.
○​ ? (nullable) → Indicates that name can store a null value if no input is given.
●​ print("Welcome, $name!"); → Prints the user’s name.
●​ $name (String Interpolation) → Used to insert variables inside strings.

Alternative way to concatenate strings:

print("Welcome, " + name!);

But using string interpolation ($name) is recommended.

Using DartPad for Online Programming

If you don’t want to install an IDE, you can use DartPad (an online Dart editor).

Steps to Use DartPad:

Instructor: Dr. Tanzila Kehkashan

16
1.​ Open your browser.
2.​ Go to dartpad.dev.
3.​ Write your Dart code in the editor.
4.​ Click on Run to execute the code.

3.3. Common Data Types in Dart


Data Description Example
Type

int Stores whole numbers int count = 10;


(integers)

double Stores decimal (floating-point) double price = 99.99;


numbers

num Can store both int and double num value = 50; or num value = 50.5;
values

bigint Stores large integers beyond BigInt bigNumber =


int range BigInt.parse('12345678901234567890'
);

String Stores text (characters) String name = "Nawaz";

bool Stores true/false values bool isLogin = true;

var Automatically detects the data var city = "New York";


type

dynamic Can change type during dynamic data = 10;


runtime data = "Hello";

3.4 Declaration and Initialization

A variable in Dart is declared using:

1.​ A data type (optional if using var or dynamic).


2.​ A variable name (identifier).
3.​ An assignment operator = to store a value.

Instructor: Dr. Tanzila Kehkashan

17
3.5. Nullable and Non-Nullable Variables

Non-Nullable Variables (Default)

By default, Dart does not allow null values for variables.

int x; // ERROR: Non-nullable variable must be initialized

Nullable Variables

To allow null, use the ? symbol.

int? age;

age = null; // This is allowed

3.6 Variable Scope and Lifetime

●​ Local Variables: Declared inside a function/block and accessible only within that block.
●​ Global Variables: Declared outside all functions and accessible throughout the program.

Scope Example

void main() {

int localVariable = 10; // Local variable

print(localVariable);

int globalVariable = 20; // Global variable

3.7. Mutable and Immutable Variables

Mutable Variables (Default)

●​ By default, Dart variables are mutable, meaning their values can change.

int score = 100;

score = 200; // Allowed

Instructor: Dr. Tanzila Kehkashan

18
Immutable Variables (final and const)

●​ final: Variable value is assigned only once but determined at runtime.


●​ const: Value is constant at compile-time.

final int maxLimit = 500;

const double pi = 3.14159;

3.8. Dynamic and Var Keywords

var Keyword

●​ Automatically detects the data type at compile-time.

var city = "New York"; // Inferred as String

var age = 30; // Inferred as int

dynamic Keyword

●​ Can change type at runtime.

dynamic value = "Hello";

value = 10; // Allowed

3.9. Conditional Operators in Dart


Dart provides several comparison operators that return Boolean values (true or false):

Operator Meaning

== Equal to

!= Not equal to

> Greater than

< Less than

Instructor: Dr. Tanzila Kehkashan

19
>= Greater than or equal to

<= Less than or equal to

3.10. If Condition
Example
void main() {
int a = 100;
if (a > 200) {
print("Block 1 executed");
} else if (a > 50) {
print("Block 2 executed");
} else if (a > 10) {
print("Block 3 executed");
} else {
print("Block 4 executed");
}
}

Output:

Block 2 executed

3.11. Logical Operators in Dart


Logical operators combine multiple conditions:

Operator Meaning Example

&& Logical AND (a > 10 && b < 20)

|| Logical OR (a > 10 || b < 20)

! Logical NOT !(a > 10)

3.12. Ternary Operator (? :)


A shorthand way to write if-else.

Instructor: Dr. Tanzila Kehkashan

20
Syntax:

condition ? expression_if_true : expression_if_false;

Example:
int a = 100;
String result = (a > 50) ? "A is large" : "A is small";
print(result);

Output:

A is large

3.13. Functions in Dart

Declaring a Function in Dart

●​ Return Type – Specifies what type of value the function will return (e.g., int, String,
double, etc.). If a function doesn’t return anything, we use void.
●​ Function Name – A unique identifier that is used to call the function.
●​ Parameters (Optional) – Input values that the function requires to perform an operation.
●​ Function Body – Contains the instructions to be executed when the function is called.

Example 1: Function Without Return Type


void printMessage() {
print("Hello, Dart!");
}

Explanation:

●​ The function printMessage() does not return any value, so its return type is void.
●​ Inside the function body, a message is printed to the console.
●​ Whenever this function is called, the message "Hello, Dart!" will be displayed.

Calling the Function


void main() {
printMessage(); // Function calling
}

Instructor: Dr. Tanzila Kehkashan

21
Output:

Hello, Dart!

Example 2: Function With Return Type


int add(int a, int b) {
int sum = a + b;
return sum;
}

Explanation:

●​ The function add(int a, int b) takes two integer parameters and returns their sum.
●​ The return type is int, so we must return an integer value.
●​ The return statement sends the result back to the calling function.

Calling the Function and Storing the Result


void main() {
int result = add(5, 7); // Function calling with arguments
print("The sum is: $result");
}

Output:

The sum is: 12

Example 3: Function with Parameters

Parameters allow functions to operate on dynamic values instead of hardcoded data.

void greet(String name) {


print("Hello, $name!");
}

void main() {
greet("Nawaz");

Instructor: Dr. Tanzila Kehkashan

22
greet("Kandan");
}

Output:

Hello, Nawaz!

Hello, Kandan!

Returning Values from Functions

A function can return a value using the return statement.

double calculateArea(double radius) {


return 3.14 * radius * radius;
}

void main() {
double area = calculateArea(5);
print("The area is: $area");
}

Output:

The area is: 78.5

Function With Parameters and Without Return Type


void greetCR(String name) {
print("Welcome, $name!");
}

void main() {
greetCR("Faisal");
greetCR("Nawaz");
}

Function Without Parameters but With Return Type

Instructor: Dr. Tanzila Kehkashan

23
int getRandomNumber() {
return 42;
}
void main() {
int number = getRandomNumber();
print("Random number is: $number");
}

Passing Arguments to Functions

Arguments are the actual values passed to a function when it is called.

void displayInfo(String name, int age) {


print("Name: $name, Age: $age");
}

void main() {
displayInfo("Sohaib", 25);
}

Output:

Name: Sohaib, Age: 25

Using Optional Positional Parameters


void showDetails(String name, [int? age]) {
print("Name: $name");
if (age != null) {
print("Age: $age");
}
}

void main() {
showDetails("Umair");
showDetails("Adil", 30);
}

Instructor: Dr. Tanzila Kehkashan

24
Named Parameters with Default Values
void introduce({String name = "Guest", int age = 18}) {
print("Name: $name, Age: $age");
}

void main() {
introduce();
introduce(name: "Imran", age: 25);
}

Higher-Order Functions (Functions as Arguments)

Functions can be passed as parameters to other functions.

void executeFunction(Function func) {


func();
}

void sayHello() {
print("Hello from a function!");
}

void main() {
executeFunction(sayHello);
}

Lambda Functions (Anonymous Functions)

Short functions written without a name.

var add = (int a, int b) => a + b;

void main() {
print(add(3, 5)); // Output: 8
}

3.14. Lists in Dart

Instructor: Dr. Tanzila Kehkashan

25
A List in Dart is an ordered collection of objects. Lists are similar to arrays in other programming
languages and allow storing multiple values in a single variable.

Creating Lists

i. Fixed-Length List (Immutable Length)

A fixed-length list has a predetermined size that cannot be changed.

void main() {
List<int> numbers = List.filled(5, 0); // Creates a list of size 5 with
default values 0
numbers[0] = 10;
numbers[1] = 20;
print(numbers); // Output: [10, 20, 0, 0, 0]
}

ii. Growable List (Dynamic Size)

A growable list can expand dynamically as elements are added.

void main() {
List<String> fruits = ["Apple", "Banana", "Cherry"];
fruits.add("Mango"); // Adding a new element
print(fruits); // Output: [Apple, Banana, Cherry, Mango]
}

List Properties
void main() {
List<int> numbers = [1, 2, 3, 4, 5];

print(numbers.length); // Output: 5 (number of elements)


print(numbers.first); // Output: 1 (first element)
print(numbers.last); // Output: 5 (last element)
print(numbers.isEmpty); // Output: false (checks if list is empty)
print(numbers.isNotEmpty); // Output: true (checks if list is not empty)
}

List Methods

Instructor: Dr. Tanzila Kehkashan

26
i. Adding Elements
void main() {
List<int> numbers = [1, 2, 3];

numbers.add(4); // Adds a single element


numbers.addAll([5, 6, 7]); // Adds multiple elements
numbers.insert(2, 99); // Inserts 99 at index 2
numbers.insertAll(1, [10, 20]); // Inserts multiple elements at index 1

print(numbers); // Output: [1, 10, 20, 2, 99, 3, 4, 5, 6, 7]


}

ii. Removing Elements


void main() {
List<String> colors = ["Red", "Green", "Blue", "Yellow"];

colors.remove("Green"); // Removes "Green" from the list


colors.removeAt(1); // Removes element at index 1
colors.removeLast(); // Removes the last element
colors.removeWhere((color) => color.startsWith("R")); // Removes elements
starting with 'R'

print(colors); // Output: ["Blue"]


}

iii. Updating Elements


void main() {
List<String> cars = ["BMW", "Tesla", "Toyota"];

cars[1] = "Mercedes"; // Replacing Tesla with Mercedes

print(cars); // Output: [BMW, Mercedes, Toyota]


}

iv. Checking Elements


void main() {
List<int> numbers = [10, 20, 30, 40];

Instructor: Dr. Tanzila Kehkashan

27
print(numbers.contains(20)); // Output: true (checks if 20 exists)
print(numbers.indexOf(30)); // Output: 2 (returns index of 30)
}

v. Sorting a List
void main() {
List<int> numbers = [5, 2, 9, 1, 7];

numbers.sort(); // Sorts in ascending order


print(numbers); // Output: [1, 2, 5, 7, 9]

numbers.sort((a, b) => b.compareTo(a)); // Sorts in descending order


print(numbers); // Output: [9, 7, 5, 2, 1]
}

vi. Reversing a List


void main() {
List<String> names = ["Nawaz", "Faisal", "Umer"];

print(names.reversed.toList());
}

vii. Iterating Over a List


void main() {
List<String> cities = ["New York", "London", "Paris"];

for (String city in cities) {


print(city);
}

// Output:
// New York
// London
// Paris
}

viii. Mapping Over a List


void main() {
List<int> numbers = [1, 2, 3];

Instructor: Dr. Tanzila Kehkashan

28
List<int> squaredNumbers = numbers.map((num) => num * num).toList();

print(squaredNumbers); // Output: [1, 4, 9]


}

ix. Filtering a List


void main() {
List<int> numbers = [10, 20, 30, 40, 50];

List<int> filtered = numbers.where((num) => num > 25).toList();

print(filtered); // Output: [30, 40, 50]


}

x. Converting Between Lists and Strings


void main() {
List<String> words = ["Hello", "World"];

String sentence = words.join(" "); // Convert list to string


print(sentence); // Output: "Hello World"

List<String> splitWords = sentence.split(" "); // Convert string to list


print(splitWords); // Output: ["Hello", "World"]
}

3.15. Maps in Dart


A Map in Dart is a collection of key-value pairs, similar to a dictionary in Python or an object in
JavaScript. It allows efficient lookups, insertions, and deletions based on unique keys.

Dart Maps are a powerful way to store key-value pairs and provide various methods for easy
manipulation. They are essential when working with structured data in Flutter and Dart
applications.

Creating a Map

i. Using Literal Syntax

Instructor: Dr. Tanzila Kehkashan

29
void main() {
Map<String, int> ages = {
"Haseeb": 25,
"Umer": 30,
"Zaka": 35
};

print(ages); // Output: {Haseeb: 25, Umer: 30, Zaka: 35}


}

ii. Using Map Constructor


void main() {
Map<String, String> countries = Map();

countries["USA"] = "Washington D.C.";


countries["UK"] = "London";
countries["India"] = "Dubai";

print(countries); // Output: {USA: Washington D.C., UK: London, India: Dubai}


}

Accessing Elements
void main() {
Map<String, int> scores = {"Fahad": 90, "Umair": 85, "Arslan": 95};

print(scores["Fahad"]); // Output: 90
print(scores["Imran"]); // Output: null (key not found)
}

Adding & Updating Values


void main() {
Map<String, int> marks = {"Math": 90, "Science": 85};

marks["English"] = 88; // Adding a new key-value pair

Instructor: Dr. Tanzila Kehkashan

30
marks["Science"] = 95; // Updating an existing key

print(marks); // Output: {Math: 90, Science: 95, English: 88}


}

Checking Keys & Values


void main() {
Map<String, int> scores = {"Mohsin": 90, "Ali": 85};

print(scores.containsKey("Mohsin")); // Output: true


print(scores.containsKey("Hussain")); // Output: false

print(scores.containsValue(85)); // Output: true


print(scores.containsValue(100)); // Output: false
}

Removing Elements
void main() {
Map<String, int> scores = {"Fahad": 90, "Umair": 85, "Arslan": 95};

scores.remove("Umair"); // Removes key "Umair"

print(scores); // Output: {Fahad: 90, Arslan: 95}


}

Iterating Over a Map

i. Using forEach()
void main() {
Map<String, int> marks = {"Math": 90, "Science": 85, "English": 88};

marks.forEach((subject, mark) {
print("$subject: $mark");
});
}

Output:

Math: 90

Instructor: Dr. Tanzila Kehkashan

31
Science: 85

English: 88

ii. Using for loop


void main() {
Map<String, String> capitals = {"USA": "Washington D.C.", "UK": "London",
"Pakistan": "Islamabad"};

for (var key in capitals.keys) {


print("$key → ${capitals[key]}");
}
}

Output:

USA → Washington D.C.

UK → London

Pakistan → Islamabad

Map Properties
void main() {
Map<String, int> numbers = {"One": 1, "Two": 2, "Three": 3};

print(numbers.keys); // Output: (One, Two, Three)


print(numbers.values); // Output: (1, 2, 3)
print(numbers.length); // Output: 3
print(numbers.isEmpty); // Output: false
print(numbers.isNotEmpty); // Output: true
}

Sorting a Map
void main() {
Map<String, int> students = {"Fahad": 90, "Umair": 85, "Arslan": 95};

var sortedKeys = students.keys.toList()..sort();


var sortedMap = {for (var key in sortedKeys) key: students[key]};

Instructor: Dr. Tanzila Kehkashan

32
print(sortedMap); // Output: {Arslan: 95, Fahad: 90, Umair: 85}
}

Mapping Values in a Map


void main() {
Map<String, int> prices = {"Apple": 10, "Banana": 5, "Mango": 15};

var discountedPrices = prices.map((fruit, price) => MapEntry(fruit, price -


2));

print(discountedPrices); // Output: {Apple: 8, Banana: 3, Mango: 13}


}

Filtering a Map
void main() {
Map<String, int> marks = {"Math": 90, "Science": 70, "English": 85};

var highScores = marks.entries.where((entry) => entry.value > 80).toList();

print(highScores); // Output: [MapEntry(Math: 90), MapEntry(English: 85)]


}

Merging Two Maps


void main() {
Map<String, int> map1 = {"A": 1, "B": 2};
Map<String, int> map2 = {"C": 3, "D": 4};

var mergedMap = {...map1, ...map2};

print(mergedMap); // Output: {A: 1, B: 2, C: 3, D: 4}


}

3.16. OOP in Dart

Defining a Class with Constructor, Properties, and Methods

Instructor: Dr. Tanzila Kehkashan

33
class Car {
// Instance Variables (Properties)
String brand;
int year;
double price;

// Constructor
Car(this.brand, this.year, this.price);

// Method to Display Car Details


void showDetails() {
print("Car Brand: $brand, Year: $year, Price: \$$price");
}
}

void main() {
// Creating Objects of Car Class
Car car1 = Car("Toyota", 2022, 25000);
Car car2 = Car("Honda", 2023, 28000);

// Calling Methods
car1.showDetails();
car2.showDetails();
}

Output:

Car Brand: Toyota, Year: 2022, Price: $25000

Car Brand: Honda, Year: 2023, Price: $28000

Types of Constructors in Dart

(a) Default Constructor

If no constructor is defined, Dart provides a default constructor that initializes objects without
parameters.

class Person {
String name = "Ali Raza Jatala"; // Default value

Instructor: Dr. Tanzila Kehkashan

34
void showName() {
print("Person's Name: $name");
}
}

void main() {
Person p = Person(); // Default constructor
p.showName();
}

(b) Parameterized Constructor

We can pass parameters to initialize object properties.

class Student {
String name;
int age;

// Parameterized Constructor
Student(this.name, this.age);
}

void main() {
Student s1 = Student("Kandan", 20);
print("${s1.name} is ${s1.age} years old");
}

(c) Named Constructor

Dart allows multiple constructors using named constructors.

class Employee {
String name;
int salary;

// Default Constructor
Employee(this.name, this.salary);

// Named Constructor
Employee.withBonus(this.name, this.salary) {
salary += 5000; // Adding Bonus

Instructor: Dr. Tanzila Kehkashan

35
}
}

void main() {
Employee e1 = Employee("Haseeb", 50000);
Employee e2 = Employee.withBonus("Umer", 50000);

print("${e1.name}'s Salary: ${e1.salary}");


print("${e2.name}'s Salary with Bonus: ${e2.salary}");
}

Output:

Haseeb's Salary: 50000

Umer's Salary with Bonus: 55000

Getters and Setters in Dart

Getters and setters control access to class properties.

class Product {
String _name = ""; // Private Variable

// Getter
String get name => _name;

// Setter
set name(String value) {
if (value.isNotEmpty) {
_name = value;
}
}
}

void main() {
Product p = Product();
p.name = "Laptop"; // Using Setter
print(p.name); // Using Getter
}

Instructor: Dr. Tanzila Kehkashan

36
Inheritance in Dart (Extending a Class)

Inheritance allows a child class to reuse properties and methods from a parent class.

class Animal {
void makeSound() {
print("Animal makes a sound");
}
}

// Child Class (Extending Animal)


class Dog extends Animal {
void bark() {
print("Dog Barks");
}
}

void main() {
Dog d = Dog();
d.makeSound(); // Inherited Method
d.bark(); // Dog's Own Method
}

Output:

Animal makes a sound

Dog Barks

Abstract Class in Dart

An abstract class cannot be instantiated and is used to define a blueprint for other classes.

abstract class Shape {


void draw(); // Abstract Method (No Body)
}

class Circle extends Shape {


void draw() {
print("Drawing a Circle");

Instructor: Dr. Tanzila Kehkashan

37
}
}

void main() {
Circle c = Circle();
c.draw();
}

Polymorphism in Dart

Polymorphism allows overriding methods in a child class.

class Animal {
void makeSound() {
print("Animal makes a sound");
}
}

class Cat extends Animal {


@override
void makeSound() {
print("Cat Meows");
}
}

void main() {
Animal a = Cat();
a.makeSound(); // Calls overridden method
}

Output:

Cat Meows

Static Variables and Methods

static properties and methods belong to the class itself, not individual objects.

class MathUtils {
static const double pi = 3.1416;

Instructor: Dr. Tanzila Kehkashan

38
static double square(double num) {
return num * num;
}
}

void main() {
print("Pi Value: ${MathUtils.pi}");
print("Square of 4: ${MathUtils.square(4)}");
}

Instructor: Dr. Tanzila Kehkashan

39
Module 4: Flutter Basics - UI Components & Widgets
4.1. Flutter Widgets Overview

4.2. Text, Buttons, and Image Widgets

4.3. Layouts: Rows, Columns & Stack

4.4. Navigation & Routing in Flutter

4.5. User Input Handling & Forms

Instructor: Dr. Tanzila Kehkashan

40
4.6. State Management Overview (Stateless vs Stateful Widgets)

Instructor: Dr. Tanzila Kehkashan

41

You might also like