Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views60 pages

Flutter Practice Problems UPDATED

The document presents a collection of Flutter practice problems organized into sections covering Dart basics, Flutter widgets, navigation, database connectivity, and advanced topics. Each section contains various programming tasks aimed at enhancing skills in Dart and Flutter, including operations on lists, sets, maps, and records. The tasks are designed to help learners practice and apply their knowledge in practical scenarios, with example inputs and outputs provided for clarity.

Uploaded by

muhammad ali
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)
5 views60 pages

Flutter Practice Problems UPDATED

The document presents a collection of Flutter practice problems organized into sections covering Dart basics, Flutter widgets, navigation, database connectivity, and advanced topics. Each section contains various programming tasks aimed at enhancing skills in Dart and Flutter, including operations on lists, sets, maps, and records. The tasks are designed to help learners practice and apply their knowledge in practical scenarios, with example inputs and outputs provided for clarity.

Uploaded by

muhammad ali
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/ 60

FLUTTER PRACTICE PROBLEMS

Dr. OSMAN KHALID


http://sites.google.com/view/osmankhalid

LAST UPDATED: 22 April 2025

Table of Contents
DART (CLO-1)........................................................................................................................................... 1
FLUTTER WIDGETS (CLO-2) ................................................................................................................... 29
NAVIGATION IN FLUTTER (CLO-3) ......................................................................................................... 45
DATABASE CONNECTIVITY IN FLUTTER (CLO-4) .................................................................................... 52
FLUTTER ADVANCED TOPICS (CLO-5).................................................................................................... 60

DART (CLO-1)

Basics
Question P1:
*Print a Welcome Message*
Write a program that prints "Welcome to Programming!" to the console.

Question A1:
Write a program that takes the command line arguments of types string, integer and
decimal value. In the case of a string, its length should be displayed, for an integer
value, it should be multiplied by 100, and for a decimal value, we need to take its
power of 3.

1
Question P2:
*Simple Arithmetic Operations*
Write a program that takes two numbers as input and outputs their sum, difference,
product, and quotient.

Question P3:
*Even or Odd*
Write a program that checks if a given number is even or odd.

Question P4:
*Find the Largest of Three Numbers*
Write a program that takes three numbers as input and outputs the largest number.

Question P6:
*Simple Interest Calculation*
Write a program to calculate the simple interest using the formula SI = (P * R * T) /
100, where P is the principal, R is the rate of interest, and T is the time period.

Question P7:
*Reverse a String*
Write a program to reverse a string entered by the user.

Question P8:
*Check for Leap Year*
Write a program that checks if a given year is a leap year or not.

2
Question P9:
*Multiplication Table*
Write a program that generates the multiplication table for a given number.

Question P10:
*Count Digits in a Number*
Write a program that counts the number of digits in an integer entered by the user.

Records
Question P11:
**Task**: Write a Dart program that defines a record type to store the name and age of a person.
Create three records for different people and print out their details.

- Define a record `(String, int)` to hold the `name` and `age`.

- Access the fields of the record and print them.

**Example Output:**

```

Name: Alice, Age: 25

Name: Bob, Age: 30

Name: Charlie, Age: 22

```

Question P12:

**Working with Lists of Records**

3
**Task**: Define a list of records to store information about students. Each student record should
contain the student’s name, age, and grade. Write a Dart program that prints the details of all
students in the list.

- Define a record `(String, int, double)` for `name`, `age`, and `grade`.

- Create a list of at least 5 student records.

- Loop through the list and print each student's details.

**Example Output:**

```

Name: John, Age: 18, Grade: 85.5

Name: Lisa, Age: 19, Grade: 90.0

...

```

Question P13:

**Sorting Records by Age**

**Task**: Create a list of person records with fields `name` and `age`. Write a program that sorts the
list by age in ascending order and prints the sorted list.

- Define a record `(String, int)` for the person's name and age.

- Sort the list by age using Dart's list sorting mechanism.

- Print the sorted list of people.

**Example Output (before sorting):**

```

Name: Alice, Age: 25

Name: Bob, Age: 30

Name: Charlie, Age: 22

```

4
**Example Output (after sorting):**

```

Name: Charlie, Age: 22

Name: Alice, Age: 25

Name: Bob, Age: 30

```

Question P14:
**Filtering Records**

**Task**: Define a list of student records where each record contains the student's `name`, `age`,
and `grade`. Write a Dart program that filters out and prints only the students with grades greater
than 75.

- Define a record `(String, int, double)` for the student details.

- Filter the list based on the `grade` field.

- Print the details of students who meet the criteria.

**Example Output:**

```

Name: John, Age: 18, Grade: 85.5

Name: Lisa, Age: 19, Grade: 90.0

Question P15:
**Updating Records**

**Task**: Write a Dart program that updates a list of product records. Each product has a `name`
and `price`. The program should increase the price of all products by 10%. After updating, print the
updated product list.

- Define a record `(String, double)` for product name and price.

- Use a loop or map to update the price of each product.

- Print the updated list of products.

**Example Output:**

```

5
Before Update:

Name: Laptop, Price: 1000.0

Name: Phone, Price: 600.0

After Update:

Name: Laptop, Price: 1100.0

Name: Phone, Price: 660.0

Lists

Question P16:

**Task**: Write a Dart program that creates a list of integers. Perform the following operations:

- Add an element to the list.

- Remove an element from the list.

- Update an element at a specific index.

- Print the final list.

**Example Input:**

```

Initial List: [10, 20, 30, 40, 50]

Add 60

Remove 20

Update 30 to 35

```

**Example Output:**

```

Final List: [10, 35, 40, 50, 60]

```

6
Question P17:

**Task**: Write a Dart program that searches for a specific element in a list of strings. If the element
is found, print its index. If not, print a message saying the element is not found.

- Create a list of string elements.

- Take input (or hardcode) the element to search.

- Use a loop or list method to find the index.

**Example Input:**

```

List: ['apple', 'banana', 'cherry', 'date']

Search for: 'cherry'

```

**Example Output:**

```

'cherry' found at index 2.

```

Question P18:

**Task**: Write a Dart program that sorts a list of integers in both ascending and descending order.
Print the list after each sorting operation.

- Create a list of integers.

- Sort the list in ascending order and print it.

- Sort the list in descending order and print it.

7
**Example Input:**

```

List: [34, 12, 56, 9, 45]

```

**Example Output:**

```

Ascending Order: [9, 12, 34, 45, 56]

Descending Order: [56, 45, 34, 12, 9]

```

Question P19:
**Task**: Write a Dart program that filters out even and odd numbers from a list of integers. Create
two new lists: one containing only even numbers and the other only odd numbers. Print both lists.

- Create a list of integers.

- Use the `where` or a loop to filter out even and odd numbers.

- Print the lists of even and odd numbers.

**Example Input:**

```

List: [11, 22, 33, 44, 55, 66, 77, 88]

```

**Example Output:**

```

Even Numbers: [22, 44, 66, 88]

Odd Numbers: [11, 33, 55, 77]

```

Question P20:

8
**Task**: Write a Dart program that merges two lists of integers into one. After merging, remove
any duplicate elements from the list and print the final list.

- Create two lists of integers.

- Merge the lists.

- Use a method like `.toSet()` to remove duplicates.

- Convert the result back to a list and print it.

**Example Input:**

```

List 1: [1, 2, 3, 4, 5]

List 2: [3, 4, 5, 6, 7]

```

**Example Output:**

```

Merged List: [1, 2, 3, 4, 5, 6, 7]

```

These tasks introduce key list operations in Dart such as addition, removal, updating elements,
sorting, searching, filtering, and merging lists, which are essential concepts for students learning
about lists.

Sets
Question P21:
**Task**: Write a Dart program that performs the following operations on a set of integers:

- Add elements to the set.

- Remove an element from the set.

- Check if a specific element exists in the set.

- Print the final set.

**Example Input:**

```

9
Initial Set: {10, 20, 30, 40}

Add: 50

Remove: 20

Check if 30 exists

```

**Example Output:**

```

Set after adding 50: {10, 20, 30, 40, 50}

Set after removing 20: {10, 30, 40, 50}

30 exists in the set.

```

Question P22:
**Task**: Write a Dart program that takes two sets of integers and finds the union of both sets. The
union should contain all unique elements from both sets.

- Create two sets of integers.

- Use the `.union()` method to combine them.

- Print the result.

**Example Input:**

```

Set 1: {1, 2, 3, 4}

Set 2: {3, 4, 5, 6}

```

**Example Output:**

```

Union of sets: {1, 2, 3, 4, 5, 6}

```

10
Question P23:
**Task**: Write a Dart program that finds the intersection of two sets of integers. The intersection
should contain only the elements that are present in both sets.

- Create two sets of integers.

- Use the `.intersection()` method to find common elements.

- Print the result.

**Example Input:**

```

Set 1: {5, 10, 15, 20}

Set 2: {10, 20, 25, 30}

```

**Example Output:**

```

Intersection of sets: {10, 20}

```

Question P24:

**Task**: Write a Dart program that computes the difference between two sets of integers. The
difference should contain only the elements present in the first set but not in the second.

- Create two sets of integers.

- Use the `.difference()` method to find the difference.

- Print the result.

**Example Input:**

```

Set 1: {1, 2, 3, 4, 5}

Set 2: {3, 4, 5, 6, 7}

```

11
**Example Output:**

```

Difference of Set 1 - Set 2: {1, 2}

```

Question P25:
**Task**: Write a Dart program that converts a list of integers with duplicate elements into a set to
remove duplicates. Then, print both the original list and the set.

- Create a list of integers with duplicate values.

- Convert the list to a set using `toSet()`.

- Print both the original list and the set (which removes duplicates).

**Example Input:**

```

List: [1, 2, 2, 3, 4, 4, 5]

```

**Example Output:**

```

Original List: [1, 2, 2, 3, 4, 4, 5]

Set (without duplicates): {1, 2, 3, 4, 5}

```

Map

Question P26:

**Task**: Write a Dart program to perform the following operations on a map that stores student
names as keys and their grades as values:

12
- Add a new key-value pair.

- Update the grade of an existing student.

- Remove a student from the map.

- Print all students and their grades.

**Example Input:**

```

Initial Map: {'Alice': 85, 'Bob': 90, 'Charlie': 88}

Add: {'David': 92}

Update Bob's grade to 95

Remove: 'Charlie'

```

**Example Output:**

```

Updated Map: {'Alice': 85, 'Bob': 95, 'David': 92}

```

Question P27:
**Task**: Write a Dart program that searches for a specific student in a map where the keys are
student names and the values are their grades. If the student exists, print their grade. If the student
does not exist, print a message saying that the student was not found.

- Create a map of student names and grades.

- Search for a student by name.

- Use `containsKey()` to check if the student exists.

**Example Input:**

```

Map: {'Alice': 85, 'Bob': 90, 'Charlie': 88}

Search for: 'Bob'

13
```

**Example Output:**

```

Bob's grade: 90

```

Question P28:
**Task**: Write a Dart program that sorts a map of city names and populations by the city names
(keys) in alphabetical order and prints the sorted map.

- Create a map of cities and their populations.

- Extract the entries, sort them by the city names (keys), and convert them back into a map.

- Print the sorted map.

**Example Input:**

```

Map: {'London': 9000000, 'Paris': 2140000, 'Berlin': 3700000}

```

**Example Output:**

```

Sorted Map: {'Berlin': 3700000, 'London': 9000000, 'Paris': 2140000}

Question P29:
**Task**: Write a Dart program that sorts a map of product names and their prices by the prices
(values) in ascending order and prints the sorted list of products.

- Create a map of products and their prices.

- Sort the map entries by values (prices) and print the sorted entries.

14
**Example Input:**

```

Map: {'Laptop': 1200, 'Phone': 800, 'Tablet': 600}

```

**Example Output:**

```

Sorted by Prices: {'Tablet': 600, 'Phone': 800, 'Laptop': 1200}

```

Question P30:
**Task**: Write a Dart program that manages a list of maps where each map contains information
about a product (`name`, `price`, `quantity`). The program should:

- Add a new product to the list.

- Find a product by its name.

- Sort the products by price.

- Create a list of product maps, each containing `name`, `price`, and `quantity`.

- Perform operations such as searching for a product and sorting the list by price.

**Example Input:**

```

Product List: [

{'name': 'Laptop', 'price': 1200, 'quantity': 5},

{'name': 'Phone', 'price': 800, 'quantity': 10},

{'name': 'Tablet', 'price': 600, 'quantity': 8}

Add: {'name': 'Headphones', 'price': 150, 'quantity': 15}

Search for: 'Phone'

```

**Example Output:**

```

15
Added Product: {'name': 'Headphones', 'price': 150, 'quantity': 15}

Found Product: {'name': 'Phone', 'price': 800, 'quantity': 10}

Sorted Products by Price: [

{'name': 'Headphones', 'price': 150, 'quantity': 15},

{'name': 'Tablet', 'price': 600, 'quantity': 8},

{'name': 'Phone', 'price': 800, 'quantity': 10},

{'name': 'Laptop', 'price': 1200, 'quantity': 5}

List of Map

Question P31:
Write a Dart program that creates a map of country names as keys and their capitals as values.
Perform the following tasks:

- Add at least 5 country-capital pairs to the map.

- Access and print the capital of "Germany".

- Check if the map contains the key "India", and print the result.

Question P32:
Create a map of students' names (keys) and their corresponding grades (values). Write a Dart
function to iterate over the map and print each student's name along with their grade.

Question P33:
Given the following map:

```dart

Map<String, int> inventory = {

'Apples': 50,

'Oranges': 30,

16
'Bananas': 20

};

```

Perform the following operations:

- Update the quantity of 'Oranges' to 45.

- Add a new item 'Mangoes' with a quantity of 60.

- Remove 'Bananas' from the map.

Print the updated map after each operation.

Question P34:
Write a Dart function that takes a list of strings as input and returns a map where the keys are
words and the values are the number of times each word appears in the list. Test the function with
the following list:

```dart

['apple', 'banana', 'apple', 'orange', 'banana', 'apple']

```

Question P35:
Write a Dart program that defines two maps:

```dart

Map<int, String> map1 = {1: 'One', 2: 'Two', 3: 'Three'};

Map<int, String> map2 = {4: 'Four', 5: 'Five'};

```

Merge `map2` into `map1` and print the result. Also, explain what happens if `map1` and `map2`
have overlapping keys.

Dart Spread Operator

17
Question P36:
Write a Dart program that combines two lists using the spread operator. Given:

```dart

List<int> list1 = [1, 2, 3];

List<int> list2 = [4, 5, 6];

```

Create a new list that combines both lists using the spread operator and prints the result.

Question P37:
Write a Dart function that accepts two nullable lists of integers and returns a new list combining
both. Use the null-aware spread operator (`...?`) to handle cases where one or both lists might be
`null`. For example:

```dart

List<int>? list1 = [1, 2, 3];

List<int>? list2 = null;

```

Test the function with various combinations of `null` and non-`null` lists.

Question P38:
Write a Dart program that merges two maps using the spread operator. Given:

```dart

Map<String, String> map1 = {'name': 'Alice', 'age': '25'};

Map<String, String> map2 = {'city': 'New York', 'country': 'USA'};

```

Create a new map that combines both `map1` and `map2` and prints the result.

18
Question P39:
Write a Dart program that uses the spread operator to build a list from multiple sources, including
other lists and individual elements. For example:

```dart

List<int> evens = [2, 4, 6];

List<int> odds = [1, 3, 5];

```

Create a new list that starts with the number 0, followed by all the elements of `evens` and `odds`,
and finally ends with the number 7.

Question P40:
Write a Dart function that takes a list of lists (nested lists) and flattens it into a single list using the
spread operator. For example, given:

```dart

List<List<int>> nestedList = [[1, 2], [3, 4], [5, 6]];

```

Return a single list: `[1, 2, 3, 4, 5, 6]`.

Dart’s Collection if, Collection for


Here are five practice problems for students to practice Dart's **collection `if`** and **collection
`for`** in list, map, and set literals:

Question P41:
Write a Dart program that creates a list representing a shopping cart. Use the **collection `if`** to
conditionally add an item "Coupon Discount" to the list only if a boolean variable `discountApplied`
is `true`. The initial cart should contain `"Apples"`, `"Bananas"`, and `"Oranges"`. Print the final list
based on whether the discount is applied or not.

```dart

bool discountApplied = true; // or false

19
```

Question P42:
Write a Dart program that generates a list of numbers from 1 to 10 using the **collection `for`**.
Then, use the **collection `if`** to include only even numbers in the final list. Print the list of even
numbers.

```dart

List<int> numbers = [for (var i = 1; i <= 10; i++) if (i % 2 == 0) i];

```

Question P43:
Create a Dart program that uses a **map literal** to store product names as keys and their prices
as values. Use the **collection `if`** to include an entry `"Discount"` only if a boolean
`applyDiscount` is `true`. If the discount is applied, the value should be a 10% deduction of the total
price. Otherwise, no discount should appear in the map.

```dart

bool applyDiscount = false; // or true

```

Question P44:
Write a Dart program that creates a **set** of favorite colors. The set should initially contain
`'Blue'`, `'Green'`, and `'Red'`. Use the **collection `if`** to include `'Purple'` only if a boolean
variable `likesPurple` is `true`. Print the final set of favorite colors.

```dart

bool likesPurple = true; // or false

```

Question P45:
Write a Dart program that generates a list of the first 10 Fibonacci numbers using the **collection
`for`**. Use the **collection `if`** to include only numbers greater than 10 in the final list. Print the
result.

```dart

List<int> fibonacci = [0, 1, for (int i = 2; i < 10; i++) fibonacci[i - 1] + fibonacci[i - 2]];

20
```

Control flow operators


Here are five practice problems for students to practice Dart's control flow operators (`if`, `else`,
`else if`, `switch`, `for`, `while`, etc.):

Question P46:
Write a Dart function that takes an integer as input and uses an `if-else` statement to determine
whether the number is even or odd. The function should print "Even" if the number is even, and
"Odd" if it’s odd. Test the function with different integer inputs.

Question P47:
Create a Dart program that takes a student's score (an integer between 0 and 100) and uses `if-else
if-else` statements to determine their grade. The grading system should be as follows:

- Score >= 90: Grade A

- Score >= 80: Grade B

- Score >= 70: Grade C

- Score >= 60: Grade D

- Score < 60: Grade F

Print the grade based on the score.

Question P48:
Write a Dart function that takes an integer between 1 and 7 as input, where each number
corresponds to a day of the week (1 for Monday, 2 for Tuesday, etc.). Use a `switch` statement to
print the name of the corresponding weekday. If the number is outside the range 1–7, print "Invalid
day".

Question P49:
Given a list of integers:

```dart

List<int> numbers = [10, 20, 30, 40, 50];

21
```

Write a Dart program that uses a `for` loop to iterate over the list and prints the square of each
number. For example, for the number 10, the program should print `100`.

Question P50:
Write a Dart function that takes a positive integer as input and uses a `while` loop to calculate the
sum of its digits. For example, if the input is `123`, the output should be `6` (1 + 2 + 3). Print the
result.

Dart’s Patterns

Here are five practice problems for students to practice patterns in Dart, which may include
destructuring, matching, and working with Dart's pattern syntax in various contexts:

Question P51:
Given a list of integers:

```dart

List<int> numbers = [10, 20, 30, 40, 50];

```

Use Dart's destructuring syntax to extract the first two elements from the list into variables and
print them. Also, assign the remaining elements to another list and print that as well.

Question P52:
Write a Dart program that defines a class `Person` with fields `name` and `age`. Create a function
that takes a `Person` object and uses a `switch` statement with object patterns to print different
messages based on the person's age group:

- If the person is younger than 18, print "Minor".

- If the person is between 18 and 60, print "Adult".

- If the person is over 60, print "Senior".

Question P53:

22
Write a Dart function that takes a `Map<String, dynamic>` representing a product with fields
`name`, `price`, and an optional `discount`. Use pattern matching to extract the `price` and `discount`
(if available), then calculate and print the final price. If no discount is present, print the original price.

Question P54:
Given the following list of lists:

```dart

List<List<int>> nestedList = [

[1, 2],

[3, 4],

[5, 6, 7]

];

```

Write a Dart program that uses pattern matching to find and print the inner list that contains
exactly 3 elements. If no such list exists, print "No match found".

Question P55:
Write a Dart function that takes a tuple (a two-element list) as an argument, where the first
element is a string representing a person's name, and the second element is an integer representing
their age. Use Dart's pattern matching in the function parameter to destructure the tuple, then print
a message like "John is 25 years old". Test the function with different tuples.

Dart’s Switch Statement

Question P56:
Write a Dart program that takes an integer between 1 and 7 as input, where each number
corresponds to a day of the week (1 for Monday, 2 for Tuesday, etc.). Use a `switch` statement to
print the name of the corresponding day. If the input number is outside the range, print "Invalid
day".

Question P57:

23
Create a Dart program that takes two numbers and an operator (`+`, `-`, `*`, or `/`) as input. Use a
`switch` statement to perform the appropriate arithmetic operation based on the input operator and
print the result. If an invalid operator is entered, print "Invalid operator".

Question P58:
Write a Dart program that simulates a traffic light system. The program should take a string as
input (`"red"`, `"yellow"`, or `"green"`) and use a `switch` statement to print the following:

- If the input is `"red"`, print "Stop".

- If the input is `"yellow"`, print "Slow down".

- If the input is `"green"`, print "Go".

- For any other input, print "Invalid signal".

Question P59:
Write a Dart function that takes the name of a month as a string (e.g., `"January"`, `"February"`)
and uses a `switch` statement to determine which season the month falls into. Print one of the
following:

- "Winter" for December, January, and February

- "Spring" for March, April, and May

- "Summer" for June, July, and August

- "Autumn" for September, October, and November

If the input is not a valid month name, print "Invalid month".

Question P60:
Write a Dart program that simulates a restaurant menu. The program should display the following
options to the user:

1. Pizza

2. Burger

3. Pasta

4. Salad

Use a `switch` statement to print the price of the selected item based on the user's input. If the
user selects an invalid option, print "Invalid choice".

24
Question A2:

Initialize a list of records, consisting of name and age values. Sort list with respect to
name and then with age.

Question A3:

Initialize a list of integers, 10, 20, 30, 40.


Create another list using the first list, such that at its initialization, the new list is
initialized like this:
Item 1: 10, Item 2: 20, Item 3: 30, Item 4: 40.

Question A4:

Suppose we have initialized a list of 4 integers. You need to sum the elements of the
list without using any loops or calling list elements through their indexes.

Question A5:

Suppose we have two numbers a=10 and b=20. You need to swap the numbers
without using any third temporary variable, or any arithmetic or logical operators.

Question A6:

Suppose you have a range of numbers, and their respective grades:


10 – 30, grade E
31 – 50, grade D
51 – 70, grade C
71 – 90, grade B
91 – 100, grade A

Write a switch – case statement, that takes the marks and show the grade.

Question B7:

Initialize a list of Map with the following items:

{"position": 10, "name": "Jawad"},

25
{"position": 33, "name": "Faisal"},

{"position": 4, "name": "Zahid"},

{"position": 6, "name": "Ali"},

{"position": 9, "name": "Noman"},

{"position": 4, "name": "Ben"},

Sort the list with first with respect to position, and then with respect to name in case
the positions are same.

Question B8:

Initialize a list of Map with the following items:

{"name":"Ali", "age":45, "marks":32 },

{"name":"Noman", "age":32, "marks":23 },

{"name":"Faisal", "age":41, "marks":43 },

{"name":"Noman", "age":11, "marks":43 },

{"name":"Faisal", "age":8, "marks":43 },

Print those records whose age is greater than 30 and whose name is either Noman
or Faisal

Question A8:
Write an example of function definition and function call with named parameters.

Question B2:
Write arrow functions for the following equations:
𝐴 = 𝑎2 + 𝑏 4
𝑍 = 𝑝2 + 5t + A

26
Question A9:
Write arrow functions for the following equations:
𝐴 = 𝑥 2 + 2𝑥𝑦 + 𝑝. 𝑍
Z = a 2 + 4.B2 – 8b + 2a
𝐵 = 𝑛2 + 𝑞𝑛 + 1

Question A10:
Suppose the equation is:
Z = x2 + 4y2 – 8N2
Where N is represented by a separate equation:
N = p2 + q2
Solve ‘Z’ with arrow function, such that you need to define the arrow function N within
the body of Z.

Question A13:

Given the following list: ['apples', 'bananas', 'oranges'];

Append a string with each element of the list and capitalize each element of list. Use
a combination of map and forEach function.

Question A14:

Create a small calculator application using typedef functions performing these


operations, add, subtract, multiply, and divide.

Question A15:
Suppose you have the following array,

List<Map<String, String>> myArray = [


{'name': 'ali', 'age': '45'},
{'name': 'noman', 'age': '34'},
];

27
Display the key and value of array elements.
Display the values of the array

Question A16:
Suppose we have the following arrays:

var myArray1 = [3, 4, 5]


var myArray2 = [6, 7, 8]

Write code to append the myArray2 into myArray1.

Question A17:
Suppose we have an Dart object { 'name': 'Devin', 'hairColor': 'brown' }
Write code to change value of hairColor using spread syntax (…) three dots.

Question A18:

Write an example of defining an arrow function within another arrow function.

Question A19:
Create a class Person with attributes: id, name, age.
Derive two classes from person, named Student and Teacher.
The extra attributes of Student are cgpa, currently enrolled semester (e.g., FA22 or
SP22, etc), admission date.
The extra attributes of Teacher are salary, designation (Lecturer, Assistant
Professor, Professor, etc), department, and joining date.
Populate a list of at least 3 records in each class using class objects.
A user should be able to search a student or teacher with the provided ID. You
should store objects of Teacher and Student in a list.
Print list of students whose cgpa is greater than 3.7.

Question A20:

28
Given the following list of objects (name, age, marks), you need to write
myObjects.where().forEach() function, so that the name, age, and marks of those
students are printed on screen whose age is greater than 25 and marks are greater
than equal to 50, and name is Alice or Bob

myObjects.add(Student(name: 'Alice', age: 25, marks: 55));


myObjects.add(Student(name: 'Bob', age: 30, marks: 50));
myObjects.add(Student(name: 'Alice', age: 27, marks: 40));
myObjects.add(Student(name: 'Charlie', age: 22, marks: 45));

Question B1:

Given the following list of objects, you need to write myObjects.where().forEach()


function, so that the name, age, and marks of those students are printed on screen
whose age is greater than 30 and name is Noman or Faisal.

Student(name:"Ali", age:45, marks:32 ),

Student(name:"Faisal", age:41, marks:43 ),

Student(name:"Noman", age:11, marks: 43),

Student(name:"Faisal", age:8, marks:43)

FLUTTER WIDGETS (CLO-2)


Question C1:
Make an app in Flutter that shows the following on screen:

29
To load an image from the assets folder in Flutter, you need to follow a few steps.
Let’s make sure everything is set up correctly:
1. Folder Structure:
o Create an assets folder in your project root directory (if it doesn’t
already exist).
o Inside the assets folder, create an images subfolder (or any other name
you prefer).
o Place your image file (banana.jpg) inside the images folder.
2. Update pubspec.yaml:
o Open your pubspec.yaml file.
o Under the flutter section, add the following lines to specify the
assets:
o flutter:
o assets:
o - assets/images/
o Make sure the indentation is correct.
3. Image Loading:
o Now you can load the image using the Image.asset widget.
o The asset name should be relative to the assets folder. In your case,
it’s "assets/images/banana.jpg".

Question C2:

30
Write a flutter app to show the grade of a student for the given marks. The marks are
passed as an argument to the constructor of the widget class computing the grade.
The computed grade is shown in the Text widget. Here is the grade distribution for
different marks ranges:
< 50 --- F
>= 50 and < 60 --- E
>= 60 and < 70 --- D
>= 70 and < 80 --- C
>= 80 and < 90 --- B
>= 90 --- A

Question C3:
Use constructor arguments to pass names of students from a Name() widget to an
Attendance() widget. The following should be the output by Attendance() widget,
where Present or Absent status is randomly generated.

Ali Khan Present


Noman Present
Faisal Absent
Javed Absent

Question C4:
Write code to add a button in Flutter. The text showing in the button should be Click
Here. When the button is clicked, a Snackbar should be shown with message “hello
world”.

Question C5:
Write the code of TextFied() widget function.
When a user enters any text in the TextField(), it is also automatically written in
another TextField() in capital letters.

31
Question C6:
Write a flutter program in which when a button is clicked, the text of first TextField()
is assigned to second TextField()

Question C7:
Write a flutter code, so that when the button is clicked, the text “hello world” should
be shown in the Text() widget, and the button should be disabled.

Question C8:
Create a simple registration page in Flutter asking for user’s email and name. When
the user clicks on register button, the information should be shown using Text
widgets. If any input is missing, snackbar message should be shown about the
missing element. Use TextEditingController() class to get values of TextField().

Question C9:
Suppose you have two TextField(), each containing a number, and a button to add
the values of the two TextField(). When the button is clicked, the values of the
TextField() are added and result should be shown in a Text() widget.

Question C10:
The following layout has three number buttons, a plus and equal operator, and a
TextField() initialized with a zero “0”.

1 2 3 + =

The user should be able to enter an expression like this: 423+35+223. When the
user press the equal button, the answer should be shown in the TextField().

Question C15:

32
Show a list of students, such that :

ID Name CGPA
1 Javed 3.0
2 Noman 2.7
3 Ali 3.7
4 Faisal 3.3
5 Shahid 4.0
6 Kamal 3.1
7 Zahid 2.3

The students whose CGPA are in the range between 2 and less than 3 should be shown in bold and
red font.

The students whose CGPA are in the range between 3 and less than 3.7 should be shown in blue font
without bold

The students whose CGPA are greater than and equal to 3.7 should be shown in italic, bold, and
green font.

Question C35:
Write code to show the following list using flutter <ListView> widget
[ {name: ‘Ali’, age: 33, city: ‘Karachi’}, {name: ‘Faisal’, age: 20, city: ‘Lahore’}, {name:
‘Noman’, age: 53, city: ‘Karachi’},]

Question C33:
We have following record of Student objects:

RegNo Name Marks


1 Ali 80
2 Noman 60
3 Faisal 40
4 Javed 55

You need to show the above record using flutter’s ListView widget. Display a 4th column in
the output that displays ‘pass’ if marks are greater than 50 and fail otherwise.
For example:

33
RegNo Name Marks Status
1 Ali 80 Pass
2 Noman 60 Pass
3 Faisal 40 Fail
4 Javed 55 Pass

Question C34:
You have a layout as given in the following.

The capital of Pakistan is <Text>

KARACHI LAHORE ISLAMABAD

You need to write a “single method” for all the three buttons. The prototype of
method is:
function button_Click(String).
In this method, you need to get the text of the button clicked. If the text is matching
with the string “ISLAMABAD”, the <Text> should be assigned value ISLAMABAD,
otherwise it remains blank.

Question D1:
Write code to show the following list using flutter GridView widget

[ {name: ‘Ali’, age: 33, city: ‘Karachi’}, {name: ‘Faisal’, age: 20, city: ‘Lahore’}, {name:
‘Noman’, age: 53, city: ‘Karachi’},]

Question C30:
Given the following design:

A B C
0 0 0
Range Range Range

(1 to 3) (4 to 6) (7 to 9)
Click Here

34
You need to generate a random number from 1 to 9. If the random number is from 1 to 3,
increment by one in text box A, if the random number is from 4 to 6, increment by one in text
box B, if the random number is between 7 to 9, increment by one in the text box C. The
program should stop executing when any of the text boxes value crosses 5.

Question C31:
We want to implement a cricket scoring game machine. It is a competition between 3 three players.
Each player has to reach a target score of 10. Each player will play at his turn (when his button is
enabled). At a player’s turn, a random number will be generated from 1 to 6, and will be added into
the existing score of the player. At one time, the button of one player is enabled who has current
turn. When a player reaches 10, his button should be disabled forever, and the competition will
continue between remaining two players. When the second player wins, the game will be over, and
the final scores and number of turns of first-two should be displayed on the screen as Match
Summary (see below). The winner is the one with the maximum current score. If the score of two
players is same, the player with lesser number of turns should be the winner.

Player 1 Player 2 Player 3

Current Score: 0 Current Score: 0 Current Score: 0


Outcome: 0 Outcome: 0 Outcome: 0
Target: 10 Target: 10 Target: 10

Turn Number: 0 Turn Number: 0 Turn Number: 0

Player 1 Player 2 Player 3

Click a button to a Generate random number from 1 to 6

Here is the first case of match summary, where the highest score player is the winner.

Match Summary

Position 1 : Player 2, Score 9, No of Turns: 4

Position 2: Player 1, Score: 5, No of Turns: 2,

Here is the second case of match summary, where both players have the same score, and the
player with the lesser number of turns is declared the winner.

Match Summary

35
Position 1 : Player 2, Score 11, No of Turns: 4

Position 2: Player 1, Score: 11, No of Turns: 6,

(In above, we are first sorting on base of score, and then on base of number of turns).

Question C32:
Suppose you want to build a game in which a random value is generated representing fire or
wood or water on button click. Another random value representing fire or wood or water is
generated for computer on button click. The winner is decided on the following priority: Fire >
Wood, Wood > Water, Water > Fire. The player that gets the higher priority value is the
winner. If both get same priority value, it is draw. Write the flutter design and code.

User value fire

Computer value wood

Winner user

Generate user Generate


value computer value

Question C38:

Suppose you have an <Text> field and two buttons. The first button is labeled as
BLUE and the second button is labeled as GREEN. When the BLUE button is
clicked, the color of text in <Text> should changed to BLUE, and when GREEN
button is clicked, the color of text in <Text> should change to GREEN..

Question C39:

RED GREEN BLUE

BLUE is clicked

Suppose you have a layout like the above. In the example, the blue button is clicked,
and its text size is increased, and text color is changed to black.

36
The buttons are created by using array of color names, and the text in the buttons is
shown in upper case. When a button is clicked, the color of the text below is
changed and the name of color is shown as shown in the above example. Moreover,
the button that is clicked has font weight changed to bold and font size increased to
indicate which button is currently clicked.

Question C11*:
You need to develop a snakes and ladders game, as shown below:

37
The snakes & ladders board can be downloaded from:

http://hancockmcdonald.com/sites/hancockmcdonald.com/files/file-
downloads/SnakesLaddersBoard.jpg

The player image can be downloaded from:

http://clipart-library.com/images/kT85jnpXc.png

(NOTE: You may change background board or player images).

The player will promote or demote based on arrival on ladder or snake head respectively. Implement
complete logic. The game should end when a player crosses last digit.

Question C37:
The following is the game board of a Tic Tac Toe game.

6 7 8

3 4 5

0 1 2

The cells are numbered from 0 to 8 (making up a total of 9 cells). You need to develop a
game to be played between two computer players A and B. Player A’s turn takes place when
a method: playerATurn() is called, whereas for player B, the method playerBTurn() is called.
During each turn, a random number is selected from 0 to 8 to represent the array index of
the player’s List, and the player’s value (either zero ‘O’ or cross ‘X’) is inserted into that
index. However, if the generated random number is already present in any of the player’s
visitedCells list, the player’s turn will be skipped, and next player will take the turn. The
following is the winning criteria of a player. For example, the player A wins if:

visitedCellsA[0].value == visitedCellsA[1].value == visitedCellsA[2].value, Or

visitedCellsA[3].value == visitedCellsA[4].value == visitedCellsA[5].value, Or

visitedCellsA[6].value == visitedCellsA[7].value == visitedCellsA[8].value.

Similarly, the player B wins if:

visitedCellsB[0].value == visitedCellsB[1].value == visitedCellsB[2].value, Or

visitedCellsB[3].value == visitedCellsB[4].value == visitedCellsB[5].value, Or

visitedCellsB[6].value == visitedCellsB[7].value == visitedCellsB[8].value.

38
Write the functions playerATurn() and playerBTurn(). Display about the winning player or
draw match.

Question C18*:
You need to create a mobile phone portrait layout:

Email
30 chars max

Name
50 chars max

Gender

Male Female

Country

Subjects
Phy Chem Bio

Skills
C++
Java
Javascript
C#

Address

Submit

39
Question C36*:
When the application in C18 opens in tablet layout (landscape), it should be shown like this:

Email 30 chars max Name 50 chars max

Gender Male Female Country

Subjects Phy Chem Bio Address

C++
Skills
Java Submit

Javascript

Question C41:
Create a login and a registration page, with proper flutter styling. Here is a sample,
but your work can be different and better than this.

40
Question C40:

Write the following layout.

E-mail Name

Country City

Address

SUBMIT

When the screen size is reduced, the layout should be changed to:

41
E-mail

Name

Country

City

Address

SUBMIT

Note that labels are showing “above” the text boxes.

Question C12*:
The following is the website view of Standford university’s computer science
department.

42
You need to re-design the above view in mobile layout as follows:
You may need to use scrolling.

43
44
NAVIGATION IN FLUTTER (CLO-3)

Question A7:

Write code that launches a screen Display from Home screen. Send two numbers
from Home to Display, where they should be shown separately in TextField widgets.

Question A11:

We have two navigation screens as shown below. Name and email are input in the
home screen and when the submit button is clicked, the values are passed to profile
screen (using RouteSettings) where they are simply displayed. You need to write the
widgets of homescreen and profilescreen.

HOME SCREEN PROFILE SCREEN

Email Email: Ali Shah

Name Name [email protected]

Submit Back

Question 2025_1:

Design a flutter app with the following details.

45
InputScreen: DisplayScreen

The inputscreen takes the values of name The display screen contains a list of map
and age in TextFields and send to the objects, e.g.. [{“id”:10, “name”:”Ali”,
DisplayScreen widget “age”:30},{“id”:20, “name”:”Javed”,
“age”:31}],
Name You need to search the name and age
_____________ . together in the list. If the record is found, it
should be displayed in the DisplayScreen
Age using Text widgets as below:
_____________ .

Search 20

Ali

30

Question A12:

Suppose we have a layout like this

0 The value is 33

RANDOM COUNTER SEND

Write code for button RANDOM such that when user click button, a random number
from one to hundred is shown in text box. Write code for button COUNTER such that
when the user click the button, the value in the TextField start incrementing. Write
code for button SEND such that when user click on button, the value in TextField is
passed to a new screen (Display) and shown as indicated in the figure.

46
Question A21:

When the user click on button in Home screen, the both strings in TextFields should
be passed separately to the Display screen where they are shown as concatenated
string in display function of Display screen.

Home Display

Abbottabad

Pakistan Abbottabad, Pakistan

CLICK

Question A22:
Pass a number from 1 to 3 from the Home screen to the Display screen. In the
Display screen, check which of the number is received, and then write the number in
words.
For example, you passed 3 from Home screen, and in Display screen, you will print
“three” as shown below.

Home Display

3
The received number is three

CLICK

Question A23:

47
Use Flutter Widgets to design following screens:

Home screen

It will show some main categories like:

COMPUTERS, LAPTOPS, HARD DRIVES, FLASH MEMORIES, ETC.

You can use lists to show above categories. Apply the proper theme and styling.

When any of the category name is clicked a new screen should open showing sub-categories of that
parent category, and the title of the page should change to the parent category.

For example, when LAPTOPS is clicked the new screen can show models of different laptops along
with their pics and prices:

The laptops should be shown as a grid.

HP Pavilion 15

Dell Inspiron

Sony Viao

And so on

When a laptop model is clicked, its individual detail should be shown on separate screen.

You can use different .dart files for different screens and then use import to call in main.dart.

Each subcategory page should have back navigation button and a button to navigate directly to the
home screen.

Please make beautiful interfaces, some samples are attached, but you can find more on flutter.dev.

48
49
Question A24:
Create an app with 4 screens, and use Tab navigation to navigate between screens

Question A26:
Create a screen with a banner having a search field with button and a single button
for sign in / sign out. When the user clicks on sign in button, the text of button
changes to sign out and vice versa..

Question A27:
Create an app with 4 screens, screen1, screen2, screen3, and screen4. Use
grouping with Tab navigation to place screen1 and screen2 in tab 1 and screen 3
and screen 4 in tab 2

Question A28:
Create an app with 4 screens, and use Drawer navigation to navigate between
screens

Question A29:

Create an app with 4 screens, screen1, screen2, screen3, and screen4. Use Drawer
navigation based grouping to place screen1 and screen2 in drawer 1 and screen 3
and screen 4 in drawer 2

Question C13:
Create the following Form

The data is input on the “input screen”.

When the user clicks the submit button, the data is sent to the “display screen” as shown below.

INPUT SCREEN

50
Email

Name

Country

Gender Male Female

Subjects Phy Chem Bio


Skills Designing

Backend

Database
Address

Submit

DISPLAY SCREEN

Email [email protected]

Name Ali Khan

Country Pakistan

Gender Male

Subjects Phy, Bio

Skills Designing, Database

Address Lahore, Gulberg

Save

Question C19:

51
Create two screens screen1 and screen2. Share global data between the screens
containing fields: name and age. Also change the values of the name and age in
screen2.

DATABASE CONNECTIVITY IN FLUTTER (CLO-4)


Question C20:

Write an application that asks for an ID from user in RecordSearch screen. When the
user enters the ID, the record is shown against the ID in the RecordView screen. The
record is fetched from SQLite Database.

Record Search Activity


View Record Activity

Enter ID ID 25
SEARCH
NAME Osman

AGE 45
ADDRESS Abbottabad
, Pakistan

Question C21:
Write a program to store the following key value pairs using Shared preferences in
Flutter. Create a function to save the information, and a function to retrieve the
information..
{‘name’:’Ali’, ‘Age’:’45}

Question C22:
You need to create a mobile application using flutter firestore database. Here is the
description of the application.
Customer:
A module to contain customers information that can purchase products from the
application
52
Products:
A module of products. Each product can have multiple pictures uploaded to fire store
file storage.
Order:
A module that contains orders for various products, the orders are placed by the
customers.
Order Details:
A module that contains order id, and information about products purchased by a
customer.
You need to:
Develop a customer module where a customer can place various orders. The
products should be maintained in a shopping cart. On checkout a textinput will be
provided to enter a fake card info.
A seller module where he can add products and can see the orders placed by the
customer. The seller should be able to complete the orders as we usually see in e-
commerce applications.

Question C14*:
Use the tab navigation or drawer navigation to show menu for the assignment.

You need to store and retrieve data from Firestore database.

The user will perform input of data in the following screen. When the submit button is clicked, the
data is uploaded in firestore as a new document in the collection “persons”. You may also need
subcollections for subjects and skills.

INPUT DATA SCREEN

53
Email

Name

Country

Gender Male Female

Subjects Phy Chem Bio


Skills Designing

Backend

Database
Address

Submit

DISPLAY ALL DATA SCREEN

Use flat list or some other list to show the data of all persons, in the following format:

Email Name Country


Select [email protected] Ali Khan Pakistan
Select [email protected] Noman Ali Afghanistan

When the user click on “select” against any record, the data is displayed in the following manner.
(Pass the email to the next screen, where the record will be fetched from firestore against the email
and showed in display screen).

DISPLAY SINGLE DATA

54
Email [email protected]

Name Ali Khan

Country Pakistan

Gender Male

Subjects Phy, Bio

Skills Designing, Database

Address Lahore, Gulberg

Edit Delete

When the user press delete button, the record should be deleted (after a confirmation alert) and the
user should be directed back to the display all data screen.

When user presses on Edit button, the edit data screen should appear where his name and address
should be in edit mode. (again, pass the email to edit screen and fetch record from db)

UPDATE DATA SCREEN

Email [email protected]

Name Ali Khan

Address Lahore, Gulberg

Update Back

55
When user clicks on Update, the record is updated. When the user click on Back, he is directed back
to the display single data screen.

SEARCH SCREEN.

Email [email protected]

Search

When the user click on search button, the email is passed to the display single data screen, where
the user’s record is displayed.

Question C19
We have the following layout with a delete button.

ID: 25

Delete

Write a method that deletes the document from firestore database whose id is 25.

Question C20:

Consider the following case study. An online shop has multiple products. Multiple
customers are registered with the shop. Each customer can place multiple orders.
Each order can contain multiple products purchased by the customer. The shop
owner wants to maintain a complete history of what products in what quantities on
what dates were purchased by which customers. Create a firestore schema to
represent the above database (consisting of collections and/or subcollections).

Question C21:
We have a following layout:
56
ID: 25 NAME: Ali ADDRESS: Supply,
Abbottabad
INSERT

Write a method that inserts value in a firestore database collection “persons”.

Question C29:

We have a following layout:

ID: 25 NAME: Ali ADDRESS: Supply,


Abbottabad
UPDATE

Write a method that update value in database against ID = 25 using firestore

Question C23:
Suppose we have the following search form:

ID: NAME: ADDRESS:

SEARCH

Based on the search fields in the above form, create a compound query to search
record in a firestore collection “persons”.

57
Question C24:
You need to insert the following document in a collection name “students” in firestore
database

Name: Ali Khan


Address:
{province: ‘punjab’, city: ‘lahore’}

1. Update the city of student from Lahore to Rawalpindi,


Solution:

Question C25:
You have a cities collection in firestore database. You need to select cities using
compound query such that state of city is ABC, country is PQR, and population is
greater than 1000.
You need to fetch record from 100th row and select the next 50 records.

Suppose you have a collection in a Firestore database storing the following values.

ID Name CGPA
View 1 Javed 3.0
View 2 Noman 2.7
View 3 Ali 3.7

When a user clicks on View button against any record, the user should be navigated to a new screen
showing the individual record of the user in console:

Question C26:

Suppose View button against ID=2 is clicked, the new screen should be showing:

ID: 2
Name: Noman
CGPA: 2.7

You need to:

58
(a) Write code to display the Flatlist

(b) Write code of the function component displaying individual user’s values.

Question C27:
Consider the following case study. An online shop has multiple products. Multiple customers
are registered with the shop. Each customer can place multiple orders. Each order can
contain multiple products purchased by the customer. The shop owner wants to maintain a
complete history of what products in what quantities on what dates were purchased by which
customers. Create a firestore schema to represent the above database (consisting of
collections and/or subcollections).

Question C28:

You need to create a web / mobile application using flutter and PHP. Here is the
description of the application.
Customer:
A table to contain customers information that can purchase products from the
website

Products:
A table of products
Order:
A table that contains orders for various products, the orders are placed by the
customers.
Order Details:
A table that contains order id, product id as foreign keys and stores which products
are ordered by a customer in a particular order.
You need to:
Develop a customer module where a customer can place various orders. The
products should be maintained in a shopping cart. On checkout a textinput will be
provided to enter a fake card info.
A seller module where he can add products and can see the orders placed by the
customer. The seller should be able to complete the orders as we usually see in e-
commerce applications.

59
FLUTTER ADVANCED TOPICS (CLO-5)
Question D3:
Take a picture from your mobile using camera SDK, and upload on Firestore database. Also store the
name of the person whose picture is taken.

Question D4:
Create an app that shows the current GPS coordinates on the button click.

Question D5:
Create a GPS tracker app by attaching a listener, so that when the listener is running, the GPS
coordinates are fetched after every few seconds automatically and stored in a file. To store values in
a file using flutter, follow this URL:

https://docs.flutter.dev/cookbook/persistence/reading-writing-files

60

You might also like