Mobile App Development Lab Manual
Mobile App Development Lab Manual
Table of Contents
DART (CLO-4) ........................................................................................................................ 1
FLUTTER WIDGETS (CLO-4) .................................................................................................. 68
NAVIGATION IN FLUTTER (CLO-4) ....................................................................................... 165
DATABASE CONNECTIVITY IN FLUTTER (CLO-5) .................................................................. 211
FLUTTER ADVANCED TOPICS (CLO-5) ................................................................................ 223
DART (CLO-4)
Basics
Question P1:
*Print a Welcome Message*
Write a program that prints "Welcome to Programming!" to the console.
void main() {
print("Welcome to Programming!");
}
1
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.
/*
Question A1:
Write a program that takes as input the command line arguments of types string,
integer and decimal value. In 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.
*/
import 'dart:math';
2
Question P2:
*Simple Arithmetic Operations*
Write a program that takes two numbers as input and outputs their sum, difference,
product, and quotient.
import 'dart:io';
void main() {
// Taking first number as input
print('Enter the first number: ');
double num1 = [Link]([Link]()!);
Question P3:
*Even or Odd*
Write a program that checks if a given number is even or odd.
void main() {
// Taking a number as input
3
} else {
print('$number is odd.');
}
}
Question P4:
*Find the Largest of Three Numbers*
Write a program that takes three numbers as input and outputs the largest number.
import 'dart:io';
void main() {
// Taking three numbers as input
print('Enter the first number: ');
double num1 = [Link]([Link]()!);
Question P6:
4
*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.
import 'dart:io';
void main() {
// Taking principal amount as input
print('Enter the principal amount (P): ');
double principal = [Link]([Link]()!);
Question P7:
*Reverse a String*
Write a program to reverse a string entered by the user.
void main() {
String str = "PAKISTAN";
print([Link]('').[Link]());
}
Question P8:
*Check for Leap Year*
Write a program that checks if a given year is a leap year or not.
import 'dart:io';
5
void main() {
// Taking a year as input
print('Enter a year: ');
int year = [Link]([Link]()!);
Question P9:
*Multiplication Table*
Write a program that generates the multiplication table for a given number.
import 'dart:io';
void main() {
// Taking a number as input
print('Enter a number: ');
int number = [Link]([Link]()!);
Question P10:
*Count Digits in a Number*
Write a program that counts the number of digits in an integer entered by the user.
6
import 'dart:io';
void main() {
// Taking an integer as input
print('Enter an integer: ');
int number = [Link]([Link]()!);
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.
**Example Output:**
```
```
void main() {
// Defining a record type to hold name and age
var person1 = ('Alice', 30);
var person2 = ('Bob', 25);
var person3 = ('Charlie', 35);
7
print('Person 1: Name = ${person1.$1}, Age = ${person1.$2}');
print('Person 2: Name = ${person2.$1}, Age = ${person2.$2}');
print('Person 3: Name = ${person3.$1}, Age = ${person3.$2}');
}
Question P12:
**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`.
**Example Output:**
```
...
```
void main() {
// Defining a record type to hold name, age, and grade
var student1 = ('Alice', 20, 85.5);
var student2 = ('Bob', 22, 90.0);
var student3 = ('Charlie', 19, 78.0);
var student4 = ('Diana', 21, 92.5);
var student5 = ('Eve', 20, 88.0);
8
// Creating a list of student records
var students = [student1, student2, student3, student4, student5];
Question P13:
**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.
```
```
```
9
Name: Bob, Age: 30
```
void main() {
var records = [
(name: "Alice", age: 25),
(name: "Bob", age: 30),
(name: "Charlie", age: 22)
];
print(records);
}
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.
**Example Output:**
```
void main() {
// Defining a record type to hold name, age, and grade
var student1 = ('Alice', 20, 85.5);
var student2 = ('Bob', 22, 70.0);
var student3 = ('Charlie', 19, 78.0);
var student4 = ('Diana', 21, 92.5);
10
var student5 = ('Eve', 20, 65.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.
**Example Output:**
```
Before Update:
After Update:
void main() {
11
// Defining a record type to hold product name and price
var product1 = ('Laptop', 1000.0);
var product2 = ('Smartphone', 500.0);
var product3 = ('Tablet', 300.0);
var product4 = ('Headphones', 100.0);
var product5 = ('Smartwatch', 200.0);
Lists
Question P16:
**Task**: Write a Dart program that creates a list of integers. Perform the following operations:
**Example Input:**
```
Add 60
12
Remove 20
Update 30 to 35
```
**Example Output:**
```
```
void main() {
// Creating a list of integers
var numbers = [10, 20, 30, 40, 50];
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.
13
- Use a loop or list method to find the index.
**Example Input:**
```
```
**Example Output:**
```
```
void main() {
// Create a list of string elements
List<String> elements = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
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.
14
- Create a list of integers.
**Example Input:**
```
```
**Example Output:**
```
```
void main() {
// Create a list of integers
List<int> numbers = [34, 7, 23, 32, 5, 62];
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.
15
- Use the `where` or a loop to filter out even and odd numbers.
**Example Input:**
```
```
**Example Output:**
```
```
void main() {
// Create a list of integers
List<int> numbers = [10, 15, 20, 25, 30, 35, 40];
Question P20:
**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.
16
- 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:**
```
```
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.
void main() {
// Create two lists of integers
List<int> list1 = [1, 2, 3, 4, 5];
List<int> list2 = [4, 5, 6, 7, 8];
Sets
Question P21:
**Task**: Write a Dart program that performs the following operations on a set of integers:
17
- Check if a specific element exists in the set.
**Example Input:**
```
Add: 50
Remove: 20
Check if 30 exists
```
**Example Output:**
```
```
void main() {
// Create a set of integers
Set<int> numbers = {1, 2, 3, 4, 5};
18
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.
**Example Input:**
```
Set 1: {1, 2, 3, 4}
Set 2: {3, 4, 5, 6}
```
**Example Output:**
```
```
void main() {
// Create two sets of integers
Set<int> set1 = {1, 2, 3, 4, 5};
Set<int> set2 = {4, 5, 6, 7, 8};
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.
19
- Use the `.intersection()` method to find common elements.
**Example Input:**
```
```
**Example Output:**
```
```
void main() {
// Create two sets of integers
Set<int> set1 = {1, 2, 3, 4, 5};
Set<int> set2 = {4, 5, 6, 7, 8};
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.
**Example Input:**
20
```
Set 1: {1, 2, 3, 4, 5}
Set 2: {3, 4, 5, 6, 7}
```
**Example Output:**
```
```
void main() {
// Create two sets of integers
Set<int> set1 = {1, 2, 3, 4, 5};
Set<int> set2 = {4, 5, 6, 7, 8};
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.
- Print both the original list and the set (which removes duplicates).
**Example Input:**
```
List: [1, 2, 2, 3, 4, 4, 5]
```
21
**Example Output:**
```
```
void main() {
// Create a list of integers with duplicate values
List<int> numbers = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9];
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:
**Example Input:**
```
22
Update Bob's grade to 95
Remove: 'Charlie'
```
**Example Output:**
```
```
void main() {
// Create a map with student names as keys and their grades as values
Map<String, String> studentGrades = {
'Alice': 'A',
'Bob': 'B',
'Charlie': 'C'
};
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.
23
- Use `containsKey()` to check if the student exists.
**Example Input:**
```
```
**Example Output:**
```
Bob's grade: 90
```
void main() {
// Create a map of student names and grades
Map<String, String> studentGrades = {
'Alice': 'A',
'Bob': 'B',
'Charlie': 'C'
};
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.
24
- Extract the entries, sort them by the city names (keys), and convert them back into a map.
**Example Input:**
```
```
**Example Output:**
```
void main() {
// Create a map of cities and their populations
Map<String, int> cityPopulations = {
'Tokyo': 37435191,
'Delhi': 29399141,
'Shanghai': 26317104,
'São Paulo': 21846507,
'Mumbai': 20411000
};
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.
25
- Create a map of products and their prices.
- Sort the map entries by values (prices) and print the sorted entries.
**Example Input:**
```
```
**Example Output:**
```
```
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:
- 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: [
26
```
**Example Output:**
```
void main() {
// Create a list of product maps
List<Map<String, dynamic>> products = [
{'name': 'Laptop', 'price': 999.99, 'quantity': 10},
{'name': 'Smartphone', 'price': 699.99, 'quantity': 20},
{'name': 'Tablet', 'price': 399.99, 'quantity': 15},
{'name': 'Smartwatch', 'price': 199.99, 'quantity': 30},
{'name': 'Headphones', 'price': 149.99, 'quantity': 25},
];
27
addProduct('Keyboard', 49.99, 50);
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:
- Check if the map contains the key "India", and print the result.
void main() {
// Create a map of country names and their capitals
Map<String, String> countryCapitals = {
'Germany': 'Berlin',
'France': 'Paris',
'Italy': 'Rome',
'Japan': 'Tokyo',
'Canada': 'Ottawa'
};
28
// Access and print the capital of "Germany"
String germanyCapital = countryCapitals['Germany'] ?? 'Not found';
print('The capital of Germany is: $germanyCapital');
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.
void main() {
// Create a map of students' names and their grades
Map<String, String> studentGrades = {
'Alice': 'A',
'Bob': 'B',
'Charlie': 'C',
'David': 'B+',
'Eve': 'A-'
};
Question P33:
Given the following map:
```dart
29
'Apples': 50,
'Oranges': 30,
'Bananas': 20
};
```
void main() {
Map<String, int> inventory = {'Apples': 50, 'Oranges': 30, 'Bananas': 20};
/**
*
- Update the quantity of 'Oranges' to 45.
- Add a new item 'Mangoes' with a quantity of 60.
- Remove 'Bananas' from the map.
*/
inventory['Oranges'] = 45;
inventory['Mangoes'] = 60;
[Link]('Bananas');
print(inventory);
}
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
```
30
// Create an empty map to store word counts
Map<String, int> wordCounts = {};
return wordCounts;
}
void main() {
// Test the function with the provided list
List<String> words = [
'apple',
'banana',
'apple',
'orange',
'banana',
'apple'
];
Map<String, int> wordCounts = countWordOccurrences(words);
Question P35:
Write a Dart program that defines two maps:
```dart
```
31
Merge `map2` into `map1` and print the result. Also, explain what happens if `map1` and
`map2` have overlapping keys.
void main() {
// Define two maps with overlapping keys
Map<int, String> map1 = {1: 'One', 2: 'Two', 3: 'Three'};
Map<int, String> map2 = {2: 'Deux', 4: 'Four'};
Question P36:
Write a Dart program that combines two lists using the spread operator. Given:
```dart
```
Create a new list that combines both lists using the spread operator and prints the result.
void main() {
List<int> A = [12, 10, 8];
List<int> B = [11, 6, 8, 7];
print(newlist);
}
32
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
```
Test the function with various combinations of `null` and non-`null` lists.
void main() {
// Test cases
List<int>? list1 = [1, 2, 3];
List<int>? list2 = [4, 5, 6];
List<int>? list3 = null;
List<int>? list4 = [7, 8, 9];
Question P38:
Write a Dart program that merges two maps using the spread operator. Given:
```dart
33
Map<String, String> map1 = {'name': 'Alice', 'age': '25'};
```
Create a new map that combines both `map1` and `map2` and prints the result.
void main() {
// Define the two maps
Map<String, String> map1 = {'name': 'Alice', 'age': '25'};
Map<String, String> map2 = {'city': 'New York', 'country': 'USA'};
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
```
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.
void main() {
// Define the lists
List<int> evens = [2, 4, 6];
List<int> odds = [1, 3, 5];
34
// Print the result
print('Combined list: $combinedList');
}
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
```
void main() {
// Example nested list
List<List<int>> nestedList = [
[1, 2],
[3, 4],
[5, 6]
];
35
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
```
void main() {
// Initial items in the shopping cart
List<String> shoppingCart = ['Apples', 'Bananas', 'Oranges'];
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
```
void main() {
// Generate a list of numbers from 1 to 10 and include only even numbers
36
List<int> evenNumbers = [
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
```
void main() {
// Define the product prices
Map<String, double> productPrices = {
'Laptop': 1000.0,
'Smartphone': 800.0,
'Tablet': 500.0
};
37
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
```
void main() {
// Initial set of favorite colors
Set<String> favoriteColors = {'Blue', 'Green', 'Red'};
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]];
```
void main() {
// Generate the first 10 Fibonacci numbers
List<int> fibonacci = [0, 1];
for (int i = 2; i < 10; i++) {
[Link](fibonacci[i - 1] + fibonacci[i - 2]);
}
38
for (var num in fibonacci)
if (num > 10) num
];
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.
void main() {
// Test the function with different integer inputs
checkEvenOrOdd(4); // Even
checkEvenOrOdd(7); // Odd
checkEvenOrOdd(10); // Even
checkEvenOrOdd(15); // Odd
checkEvenOrOdd(0); // Even
}
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:
39
- Score >= 90: Grade A
void main() {
// Test the function with different scores
determineGrade(95); // Grade A
determineGrade(85); // Grade B
determineGrade(75); // Grade C
determineGrade(65); // Grade D
determineGrade(55); // Grade F
}
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".
40
case 2:
print('Tuesday');
break;
case 3:
print('Wednesday');
break;
case 4:
print('Thursday');
break;
case 5:
print('Friday');
break;
case 6:
print('Saturday');
break;
case 7:
print('Sunday');
break;
default:
print('Invalid day');
}
}
void main() {
// Test the function with different inputs
printWeekday(1); // Monday
printWeekday(4); // Thursday
printWeekday(7); // Sunday
printWeekday(0); // Invalid day
printWeekday(8); // Invalid day
}
Question P49:
Given a list of integers:
```dart
```
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`.
void main() {
41
// List of integers
List<int> numbers = [10, 20, 30, 40, 50];
// Iterate over the list and print the square of each number
for (int number in numbers) {
print('The square of $number is ${number * number}');
}
}
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.
void main() {
// Test the function with different inputs
sumOfDigits(123); // The sum of the digits of 123 is 6
sumOfDigits(456); // The sum of the digits of 456 is 15
sumOfDigits(789); // The sum of the digits of 789 is 24
}
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:
42
Given a list of integers:
```dart
```
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.
void main() {
// Given list of integers
List<int> numbers = [10, 20, 30, 40, 50];
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:
class Person {
String name;
int age;
43
Person([Link], [Link]);
}
void main() {
// Test the function with different Person objects
Person person1 = Person('Alice', 17);
Person person2 = Person('Bob', 25);
Person person3 = Person('Charlie', 65);
Question P53:
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.
44
// Print the final price
if (discount > 0) {
print(
'The final price after a discount of $discount% is: \$${[Link](2)}');
} else {
print('The original price is: \$${[Link](2)}');
}
}
void main() {
// Test the function with different products
Map<String, dynamic> product1 = {
'name': 'Laptop',
'price': 1000.0,
'discount': 10.0
};
Map<String, dynamic> product2 = {'name': 'Smartphone', 'price': 800.0};
calculateFinalPrice(
product1); // The final price after a discount of 10.0% is: $900.00
calculateFinalPrice(product2); // The original price is: $800.00
}
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".
void main() {
// Given list of lists
List<List<int>> nestedList = [
45
[1, 2],
[3, 4],
[5, 6, 7]
];
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.
void main() {
// Test the function with different tuples
printPersonInfo(['John', 25]); // John is 25 years old
printPersonInfo(['Alice', 30]); // Alice is 30 years old
printPersonInfo(['Bob', 22]); // Bob is 22 years old
}
46
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".
void main() {
int day = 3;
Question P57:
47
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".
import 'dart:io';
void main() {
// Prompt the user to enter the first number
print('Enter the first number:');
double? num1 = [Link]([Link]()!);
48
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:
import 'dart:io';
void main() {
// Prompt the user to enter a traffic light signal
print('Enter a traffic light signal (red, yellow, green):');
String? signal = [Link]()?.toLowerCase();
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:
49
- "Spring" for March, April, and May
void main() {
// Test the function with different month names
determineSeason('January'); // Winter
determineSeason('April'); // Spring
determineSeason('July'); // Summer
determineSeason('October'); // Autumn
determineSeason('Invalid'); // Invalid month
}
Question P60:
50
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".
import 'dart:io';
void main() {
// Display the menu options
print('Restaurant Menu:');
print('1. Pizza');
print('2. Burger');
print('3. Pasta');
print('4. Salad');
51
Question A2:
Initialize a list of records, consisting of name and age values. Sort list with respect to
name and then with age.
/*
Create a list of records, consisting of name and age values. Sort list with respect to
name and age.
*/
var records = [
(name: 'Ali', age: 45),
(name: 'Javed', age: 54),
(name: 'Salman', age: 36),
(name: 'Ben', age: 36),
(name: 'Javed', age: 45),
];
[Link]((a, b) {
var result = [Link]([Link]);
if( result == 0)
{
return [Link](([Link]));
}
else
{
return result;
}
});
Question A3:
52
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.
/*
Create 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.
*/
print(newlist);
}
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.
/*
Suppose we have 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:
53
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.
/*
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.
*/
(a, b) = (b, a );
print(a);
print(b);
Question A6:
Write a switch – case statement, that takes the marks and show the grade.
/*
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.
*/
switch(num)
{
case >= 10 && <= 30:
54
print("grade E");
break;
Question B7:
Sort the list with first with respect to position, and then with respect to name in case
the positions are same.
void main() {
List<Map<String, dynamic>> students = [
55
{"position": 4, "name": "Zahid"},
];
[Link]((a, b) {
var test = a["position"].compareTo(b["position"]);
if( test == 0 )
return a["name"].compareTo(b["name"]);
else
return test;
});
print(students);
Question B8:
Print those records whose age is greater than 30 and whose name is either Noman
or Faisal
void main() {
56
{"name":"Ali", "age":45, "marks":32 },
];
);
Question A8:
Write an example of function definition and function call with named parameters.
/*
Write an example of function definition and function call with named parameters.
*/
void main() {
print(ans);
57
Question B2:
Write arrow functions for the following equations:
𝐴 = 𝑎2 + 𝑏 4
𝑍 = 𝑝2 + 5t + A
/*
Write arrow functions for the following equations:
*/
void main() {
print( Z(2,3) );
Question A9:
Write arrow functions for the following equations:
𝐴 = 𝑥 2 + 2𝑥𝑦 + 𝑝. 𝑍
Z = a 2 + 4.B2 – 8b + 2a
𝐵 = 𝑛2 + 𝑞𝑛 + 1
/*
Write arrow functions for the following equations:
*/
import 'dart:math';
void main() {
print( A(1, 2, 3) );
58
var A = (int x, int y, int p) => x*x + 2*x*y + p*Z(2,3);
var Z = (int a, int b) => a*a + 4 * pow( B(1,2), 2) - 8*b + 2*a;
var B = (int n, int q) => n*n + q*n + 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.
import 'dart:math';
void main() {
print(Z(4, 5)(3, 4));
}
Question A13:
Append a string with each element of the list and capitalize each element of list. Use
a combination of map and forEach function.
/*
Question A13:
Append a string with each element of the list and capitalize each element of list.
Use a combination of map and forEach function.
*/
void main() {
59
var list = ['apples', 'bananas', 'oranges'];
Question A14:
/*
Question A14:
Create a small calculator application using typedef functions performing these
operations, add, subtract, multiply, and divide.
*/
void main() {
Calculator myfunction;
myfunction = addition;
print( myfunction(5, 6));
myfunction = subtraction;
print( myfunction(7, 3));
myfunction = multiplication;
print( myfunction(2, 3));
myfunction = division;
print( myfunction(9, 3));
60
double multiplication(double a, double b) {
return a*b;
}
Question A15:
Suppose you have the following array,
/*
Question A15:
Suppose you have the following array,
*/
void main() {
List<Map<String, String>> myArray = [
{'name': 'ali', 'age': '45'},
{'name': 'noman', 'age': '34'},
];
61
print('$key: $value');
});
}
Question A16:
Suppose we have the following arrays:
/*
Question A16:
Suppose we have the following arrays:
*/
void main() {
print(appended);
62
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 A17:
Suppose we have an Dart object { name: 'Devin', hairColor: 'brown' }
Write code to change value of hairColor using spread syntax (…) three dots.
*/
void main() {
print("Before change");
print(object);
print("After change");
print(object);
}
Question A18:
import 'dart:math';
final outerFunction = (int x) => (int y) => x + pow(y, 3);
void main() {
// Usage
63
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 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.
*/
class Person {
String? id;
String? name;
int? age;
64
}
void main() {
List<Student> students = [
Student('123', 'John Doe', 21, 3.1, 'Fa23', '2022-09-01'),
Student('456', 'Shahid Gul', 12, 2.8, 'Fa22', '2023-09-01'),
Student('432', 'Muneeza Malik', 21, 3.9, 'Sp22', '2023-10-01'),
Student('789', 'Javed Henry', 30, 2.9, 'Sp23', '2025-09-01'),
Student('728', 'Neelam Khan', 30, 3.7, 'Sp23', '2025-09-01'),
];
List<Teacher> teachers = [
Teacher('444', 'Noman Ali', 21, 31000, 'AP', 'CS', '2022-09-01'),
Teacher('666', 'Ali Shahid', 12, 28000, 'Lecturer', 'EE', '2023-09-01'),
Teacher('777', 'Qasim Khan', 30, 29000, 'AssocProf', 'MS', '2025-09-01'),
];
String studentId='456';
for(Student s in students) {
if([Link] == studentId) {
print("Student found");
break;
}
}
String teacherId='777';
for(Teacher t in teachers) {
if([Link] == teacherId) {
print("Teacher found");
break;
65
}
}
Question A20:
Given the following list of objects (name, age, marks), you need to write
[Link]().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
/*
Question A20:
*/
class Student {
String? name;
int? age;
double? marks;
66
void main() {
Question B1:
class Student{
String? name;
int? age;
int? marks;
67
}
void main() {
var mylist = [
];
);
68
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:
flutter:
assets:
- images/
import 'package:flutter/[Link]';
69
void main() {
runApp(const MyApp());
const MyApp({[Link]});
@override
return MaterialApp(
home: Scaffold(
appBar: AppBar(
),
child: Column(
mainAxisAlignment: [Link],
children: [
SizedBox(height: 20),
],
),
70
),
),
);
@override
return Container(
width: 200,
height: 200,
decoration: BoxDecoration(
borderRadius: [Link](10),
),
child: Column(
mainAxisAlignment: [Link],
children: [
71
[Link](imagePath, width: 100, height: 100),
Text(
fruitName,
),
],
),
);
Question C2:
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
import 'package:flutter/[Link]';
72
void main() {
runApp(const MyApp());
}
const MyApp({[Link]});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Grade Calculator'),
),
body: const Center(
child: GradeCalculator(marks: 65), // Example: Pass the marks here
),
),
);
}
}
String calculateGrade() {
if (marks < 50) {
return 'F';
} else if (marks >= 50 && marks < 60) {
return 'E';
} else if (marks >= 60 && marks < 70) {
return 'D';
} else if (marks >= 70 && marks < 80) {
return 'C';
} else if (marks >= 80 && marks < 90) {
return 'B';
} else {
return 'A';
}
}
@override
Widget build(BuildContext context) {
final grade = calculateGrade();
return Text(
73
'Grade: $grade',
style: const TextStyle(fontSize: 24, fontWeight: [Link]),
);
}
}
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.
import 'package:flutter/[Link]';
import 'dart:math'; // For random number generation
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Student Attendance'),
),
body: const Center(
child: Attendance(names: ['Ali Khan', 'Noman', 'Faisal', 'Javed']),
),
),
);
}
}
74
class Attendance extends StatelessWidget {
final List<String> names;
String getRandomStatus() {
final random = Random();
return [Link]() ? 'Present' : 'Absent';
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: [Link],
children: [
for (var name in names)
Padding(
padding: const [Link](8.0),
child: Text('$name\t\t${getRandomStatus()}'),
),
],
);
}
}
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”.
import 'package:flutter/[Link]';
void main() {
runApp( MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Button Example'),
),
body: const MyApp(),
75
)
)
);
}
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () {
// Show a Snackbar when the button is clicked
[Link](context).showSnackBar(
const SnackBar(
content: Text('Hello, world!'),
backgroundColor: [Link],
),
);
},
child: const Text('Click Here'),
),
);
}
}
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.
/*
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.
*/
76
import 'package:flutter/[Link]';
void main() {
runApp(const MaterialApp(
home: Scaffold(
body: Center(
child: InputDisplay(),
)
)
));
}
@override
State<InputDisplay> createState() => _InputDisplayState();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: [Link],
children: <Widget>[
TextField(
onChanged: (value) => setState(() => userInput = value
),
decoration: const InputDecoration(
hintText: 'Enter your message'
),
),
TextField(
controller: TextEditingController(text: [Link]()),
decoration: const InputDecoration(
hintText: 'Enter your message'
),
),
77
],
);
}
Question C6:
Write a flutter program in which when a button is clicked, the text of first TextField()
is assigned to second TextField()
/*
Question C6:
Write a flutter program in which when a button is clicked, the text of first TextField()
is assigned to second TextField()
*/
import 'package:flutter/[Link]';
void main() {
runApp(const MaterialApp(
home: Scaffold(
body: Center(
child: InputDisplay(),
)
)
));
}
@override
State<InputDisplay> createState() => _InputDisplayState();
}
78
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: [Link],
children: <Widget>[
TextField(
onChanged: (value) => setState(() => userInput = value
),
decoration: const InputDecoration(
hintText: 'Enter your message'
),
),
() {
message = userInput;
TextField(
controller: TextEditingController(text: message),
decoration: const InputDecoration(
hintText: 'Enter your message'
),
),
],
);
}
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.
79
/*
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.
*/
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
@override
_MyHomePageState createState() => _MyHomePageState();
}
void _showHelloWorld() {
setState(() {
isButtonDisabled = true;
});
// Show a Snackbar with "Hello, world!"
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Button Example'),
),
80
body: Center(
child: Column(
mainAxisAlignment: [Link],
children: [
Text(
isButtonDisabled ? 'Hello, world!' : '',
style: const TextStyle(fontSize: 20),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: isButtonDisabled ? null : _showHelloWorld,
child: const Text('Click Here'),
),
],
),
),
);
}
}
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 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().
*/
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
State<MyApp> createState() => _MyAppState();
}
81
class _MyAppState extends State<MyApp> {
// Controllers to store text from each box
final TextEditingController _textController1 = TextEditingController();
final TextEditingController _textController2 = TextEditingController();
String _displayText = ""; // Variable to store combined text
void _onPressed() {
// Combine text from controllers and update display text
setState(() {
_displayText = "${_textController1.text} - ${_textController2.text}";
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Simple Registration Page'),
),
body: Center(
child: Column(
mainAxisAlignment: [Link],
children: [
TextField(
controller: _textController1,
decoration: const InputDecoration(
hintText: 'Enter Email',
),
),
const SizedBox(height: 10),
TextField(
controller: _textController2,
decoration: const InputDecoration(
hintText: 'Enter Name',
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _onPressed,
child: const Text('Register'),
),
const SizedBox(height: 10),
Text(_displayText),
],
),
),
),
);
82
}
}
Output:
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.
/*
83
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.
*/
import 'package:flutter/[Link]';
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Center(
child: Counter(),
),
),
),
);
}
const Counter({[Link]});
@override
State<Counter> createState() => _CounterState();
}
int _sum = 0;
void _sumcounter() {
setState(() {
int c1=0;
int c2=0;
84
_sum = c1 + c2;
});
@override
Widget build(BuildContext context) {
return Column( // Use Column for vertical layout
mainAxisAlignment: [Link], // Center the content vertically
children: <Widget>[
TextField(
controller: _counter1,
) ,// Spacing between elements
TextField(
controller: _counter2,
),
ElevatedButton(
onPressed: _sumcounter,
child: const Text('Sum'),
),
Text("$_sum")
],
);
}
}
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().
/*
The following layout has three number buttons, a plus and equal operator, and a
TextField() initialized with a zero “0”.
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().
85
*/
import 'package:flutter/[Link]';
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Calculator'),
),
body: const MyApp()
),
)
);
}
@override
State<MyApp> createState() => _MyAppState();
}
86
},
);
setState(() {
if([Link]("Clear")==0) {
_mainscreen.text = "";
}
else if([Link]('=') == 0 )
{
if([Link]("+")==0)
{
callAlert("Invalid expression");
_mainscreen.text = "";
return;
}
int sum=0;
for(var item in tokens) {
sum = sum + [Link](item);
}
_mainscreen.text = "$sum";
}
// if the current button (btntext) pressed is same to the previous button
// and the previous button pressed was plus +
else if( ([Link](btntext) == 0 && [Link]("+") == 0) ) {
callAlert("Cannot press an '+' here");
}
else {
previous = btntext;
_mainscreen.text = "${_mainscreen.text}$btntext";
}
});
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: [Link],
children: [
TextField(
controller: _mainscreen,
decoration: const InputDecoration(
hintText: '0',
87
),
),
const SizedBox(height: 10),
Row(
children: [
ElevatedButton(
onPressed: ()=>_onPressed("1"),
child: const Text('1'),
),
const SizedBox(width: 10),
ElevatedButton(
onPressed: ()=>_onPressed("2"),
child: const Text('2'),
),
const SizedBox(width: 10),
ElevatedButton(
onPressed: ()=>_onPressed("3"),
child: const Text('3'),
),
const SizedBox(width: 10),
ElevatedButton(
onPressed: ()=>_onPressed("+"),
child: const Text('+'),
),
const SizedBox(width: 10),
ElevatedButton(
onPressed: ()=>_onPressed("="),
child: const Text('='),
),
const SizedBox(width: 10),
],
),
ElevatedButton(
onPressed: ()=>_onPressed("Clear"),
child: const Text('Clear'),
),
]
);
}
}
Question C15:
Show a list of students, such that :
ID Name CGPA
1 Javed 3.0
88
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 C15:
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
*/
import 'package:flutter/[Link]';
89
class Student {
final int id;
final String name;
final double gpa;
void main() {
runApp(MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: [Link](seedColor: [Link]),
useMaterial3: true,
),
home: MyApp()));
}
90
}
return TextStyle(
fontWeight: fw,
fontStyle: fs,
color: color,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const [Link](50),
child: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
final item = students[index];
return ListTile(
title: Row(
mainAxisAlignment: [Link],
children: [
Text("${[Link]}", style: newstyle),
Text([Link], style: newstyle),
Text("${[Link]}", style: newstyle),
]));
})));
}
}
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 C35:
91
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'},]
*/
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(title: 'Flutter Demo', home: MyApp()));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const [Link](20),
child: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
final item = students[index];
return ListTile(
subtitle: Row(children: [
Expanded(child: Text(item["name"])),
Expanded(child: Text(item["age"])),
Expanded(child: Text(item["city"])),
]));
})));
}
}
Output:
92
Question C35A:
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’},].
Now add the styling to the same example so that it should look like the following:
93
Answer:
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(title: 'Flutter Demo', home: MyApp()));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Student List'),
94
backgroundColor: [Link],
),
body: Container(
padding: const [Link](16),
child: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
final item = students[index];
return Card(
elevation: 5,
margin: const [Link](vertical: 8),
shape: RoundedRectangleBorder(
borderRadius: [Link](10),
),
child: ListTile(
contentPadding: const [Link](16),
leading: CircleAvatar(
backgroundColor: [Link].shade700,
child: Text(
item['name'][0],
style: const TextStyle(color: [Link]),
),
),
title: Text(
item["name"],
style: const TextStyle(
fontWeight: [Link],
fontSize: 18,
),
),
subtitle: Column(
crossAxisAlignment: [Link],
children: [
const SizedBox(height: 4),
Text("Age: ${item["age"]}"),
Text("City: ${item["city"]}"),
],
),
trailing: Icon(
Icons.arrow_forward_ios,
color: [Link].shade600,
),
onTap: () {
// Add action on tap if needed
},
),
95
);
},
),
),
);
}
}
Question C33:
We have following record of Student objects:
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:
Solution
/*
Question C33:
96
RegNo Name Marks
1 Ali 80
2 Noman 60
3 Faisal 40
4 Javed 55
You need to show the above record map function 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:
1 Ali 80 Pass
2 Noman 60 Pass
3 Faisal 40 Fail
4 Javed 55 Pass
*/
Example output:
97
import 'package:flutter/[Link]';
class Student {
final int regno;
void main() {
runApp(MaterialApp(title: 'Flutter Demo', home: MyApp()));
}
98
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: const [Link](20),
child: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
final item = students[index];
return ListTile(
subtitle: Row(children: [
Expanded(child: Text("${[Link]}")),
Expanded(child: Text([Link])),
Expanded(child: Text("${[Link]}")),
Expanded(child: Text([Link] >= 50 ? "Pass" : "Fail")),
]));
})));
}
}
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’},]
/*
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’},]
*/
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
99
final List<Map<String, dynamic>> users = [
{'name': 'Ali', 'age': 33, 'city': 'Karachi'},
{'name': 'Faisal', 'age': 20, 'city': 'Lahore'},
{'name': 'Noman', 'age': 53, 'city': 'Karachi'},
];
@override
Widget build(BuildContext context) {
const title = 'Grid List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: const Text(title),
),
body: [Link](
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this produces 2 rows.
crossAxisCount: 2,
// Generate 100 widgets that display their index in the List.
children: [Link]([Link], (index) {
return Card(
elevation: 4.0,
child: Padding(
padding: const [Link](8.0),
child: Column(
mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: <Widget>[
Text('Name: ${users[index]['name']}',
style: const TextStyle(
fontSize: 16.0, fontWeight: [Link])),
const SizedBox(height: 10.0),
Text('Age: ${users[index]['age']}',
style: const TextStyle(fontSize: 14.0)),
const SizedBox(height: 10.0),
Text('City: ${users[index]['city']}',
style: const TextStyle(fontSize: 14.0)),
],
),
),
);
}),
),
),
);
}
}
100
Question D1A:
Write a GridView to show by default 2 columns in Portrait layout, and then landscape
layout, it should show more items per row, as the following:
Solution:
import 'package:flutter/[Link]';
101
if (crossAxisCount < 2) {
crossAxisCount = 2; // Ensure at least 2 items in portrait layout
}
return [Link](
crossAxisCount: crossAxisCount,
children: [Link](20, (index) {
return Container(
margin: [Link](8.0),
color: [Link],
child: Center(
child: Text(
'Item $index',
style: TextStyle(color: [Link]),
),
),
);
}),
);
},
);
}
}
102
Note: to make it one column per row at portrait layout, remove these lines:
if (crossAxisCount < 2) {
crossAxisCount = 2; // Ensure at least 2 items in portrait layout
}
Question C34:
You have a layout as given in the following.
103
The capital of Pakistan is <Text>
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 C34:
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.
*/
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(title: 'Flutter Demo', home: MyApp()));
}
104
void button_click(String city) {
debugPrint("CITY $city");
setState(() {
cityInfo = city == "ISLAMABAD" ? "ISLAMABAD" : "";
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: [Link],
children: [
Text("The capital of Pakistan is ${cityInfo}"),
Row(children: [
ElevatedButton(
onPressed: () => button_click("KARACHI"), child: Text("KARACHI")),
ElevatedButton(
onPressed: () => button_click("LAHORE"), child: Text("LAHORE")),
ElevatedButton(
onPressed: () => button_click("ISLAMABAD"),
child: Text("ISLAMABAD")),
])
],
));
}
}
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
105
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.
import 'dart:math';
import 'package:flutter/[Link]';
void _incrementValue() {
if (!isRunning) return;
setState(() {
if (randomNumber >= 1 && randomNumber <= 3) {
valueA++;
} else if (randomNumber >= 4 && randomNumber <= 6) {
valueB++;
} else if (randomNumber >= 7 && randomNumber <= 9) {
106
valueC++;
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const [Link](16.0),
child: Column(children: [
Row(
mainAxisAlignment: [Link],
children: [
Column(
children: [
Text("A"),
Text('$valueA', style: TextStyle(fontSize: 24.0)),
Text("Range"),
Text("1 to 3")
],
),
Column(children: [
Text("B"),
Text('$valueB', style: TextStyle(fontSize: 24.0)),
Text("Range"),
Text("4 to 6")
]),
Column(
children: [
Text("C"),
Text('$valueC', style: TextStyle(fontSize: 24.0)),
Text("Range"),
Text("7 to 9")
],
),
],
),
Row(
mainAxisAlignment: [Link],
children: [
ElevatedButton(
onPressed: isRunning == true ? _incrementValue : null,
child: Text('Click Here'),
),
107
],
)
]),
);
}
}
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.
Here is the first case of match summary, where the highest score player is the winner.
Match Summary
108
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
(In above, we are first sorting on base of score, and then on base of number of turns).
import 'dart:math';
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scoring Game Machine',
theme: ThemeData(
primarySwatch: [Link],
),
home: const GameScreen(),
);
}
}
class Player {
int? playerNo;
int? currentScore;
int? turnNumber;
bool? buttonStatus;
bool? enabled;
Player(
{[Link],
[Link],
[Link],
[Link],
[Link]});
}
109
const GameScreen({[Link]});
@override
State<GameScreen> createState() => _GameScreenState();
}
@override
State<PlayerWidget> createState() => _PlayerWidgetState();
}
List<Player> players = [
Player(
playerNo: 1,
currentScore: 0,
turnNumber: 0,
buttonStatus: true,
enabled: true),
Player(
playerNo: 2,
currentScore: 0,
turnNumber: 0,
buttonStatus: false,
enabled: true),
Player(
playerNo: 3,
currentScore: 0,
110
turnNumber: 0,
buttonStatus: false,
enabled: true),
];
setState(() {
turnoutcome = score;
if (player == 0) {
players[0].buttonStatus = false;
players[0].currentScore = players[0].currentScore! + score;
players[0].turnNumber = players[0].turnNumber! + 1;
players[1].buttonStatus = true;
if (players[2].enabled == false) {
players[0].buttonStatus = true;
}
} else if (player == 2) {
players[0].buttonStatus = true;
111
players[1].buttonStatus = false;
players[2].buttonStatus = false;
players[2].currentScore = players[2].currentScore! + score;
players[2].turnNumber = players[2].turnNumber! + 1;
int count = 0;
for (int i = 0; i < [Link]; i++) {
if (players[i].enabled == false) {
count = count + 1;
}
}
if (count == [Link] - 1) {
showsummary = true;
[Link]((a, b) {
int ans = b['Score'].compareTo(a['Score']);
if (ans == 0) {
return a['Turns'].compareTo(b['Turns']);
} else {
return ans;
}
});
players[0].buttonStatus = false;
players[1].buttonStatus = false;
players[2].buttonStatus = false;
}
});
}
@override
Widget build(BuildContext context) {
112
return Column(
children: [
Row(
mainAxisAlignment: [Link],
children: [
Column(
children: [
Text("Player: ${players[0].playerNo}"),
Text("Outcome: $turnoutcome"),
Text("Current Score: ${players[0].currentScore}"),
Text("Target: $targetScore"),
Text("Turn Numbrer: ${players[0].turnNumber}"),
ElevatedButton(
onPressed: players[0].buttonStatus == true &&
players[0].enabled == true
? () => playerTurn(0)
: null,
style:
[Link](fixedSize: const Size(100, 50)),
child: Text('Player ${players[0].playerNo}'),
),
],
),
Column(
children: [
Text("Player: ${players[1].playerNo}"),
Text("Outcome: $turnoutcome"),
Text("Current Score: ${players[1].currentScore}"),
Text("Target: $targetScore"),
Text("Turn Numbrer: ${players[1].turnNumber}"),
ElevatedButton(
onPressed: players[1].buttonStatus == true &&
players[1].enabled == true
? () => playerTurn(1)
: null,
style:
[Link](fixedSize: const Size(100, 50)),
child: Text('Player ${players[1].playerNo}'),
),
],
),
Column(
children: [
Text("Player: ${players[2].playerNo}"),
Text("Outcome: $turnoutcome"),
Text("Current Score: ${players[2].currentScore}"),
Text("Target: $targetScore"),
Text("Turn Numbrer: ${players[2].turnNumber}"),
ElevatedButton(
onPressed: players[2].buttonStatus == true &&
113
players[2].enabled == true
? () => playerTurn(2)
: null,
style:
[Link](fixedSize: const Size(100, 50)),
child: Text('Player ${players[2].playerNo}'),
),
],
),
],
),
showsummary == true
? MatchSummary(matchSummary: matchSummary)
: const SizedBox()
],
);
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
const SizedBox(height: 20),
const Text('Match Summary'),
for (int i = 0; i < [Link]; i++)
Text(
"Position: ${i + 1}: Player: ${matchSummary[i]['Player']} Score:
${matchSummary[i]['Score']} Turns: ${matchSummary[i]['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.
114
User value fire
Winner user
import 'dart:math';
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(home: FireWoodWater()));
}
int? compRand;
String compVal = "";
bool compbtn = true;
int? userRand;
String userVal = "";
bool userbtn = true;
115
if (userVal != "" && compVal != "") {
if (userVal == "Fire" && compVal == "Fire") {
winner = "Draw";
} else if (userVal == "Fire" && compVal == "Wood") {
winner = "User";
} else if (userVal == "Fire" && compVal == "Water") {
winner = "Computer";
} else if (userVal == "Wood" && compVal == "Fire") {
winner = "Computer";
} else if (userVal == "Wood" && compVal == "Wood") {
winner = "Draw";
} else if (userVal == "Wood" && compVal == "Water") {
winner = "User";
}
if (userVal == "Water" && compVal == "Fire") {
winner = "User";
} else if (userVal == "Water" && compVal == "Wood") {
winner = "Computer";
} else if (userVal == "Water" && compVal == "Water") {
winner = "Draw";
}
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Center(child: Text('Fire, wood, water'))),
body: Padding(
padding: [Link](left: 50),
child: Column(
crossAxisAlignment: [Link],
children: [
Row(
crossAxisAlignment: [Link],
children: [
Expanded(
child: Text("User Value"),
),
SizedBox(width: 20), // Space between columns
Expanded(
child: Text(userVal),
),
],
),
Row(
crossAxisAlignment: [Link],
children: [
116
Expanded(
child: Text("Computer Value"),
),
SizedBox(width: 20), // Space between columns
Expanded(
child: Text(compVal),
),
],
),
Row(
crossAxisAlignment: [Link],
children: [
Expanded(
child: Text("Winner"),
),
Expanded(
child: Text(winner!),
),
],
),
SizedBox(height: 15),
Row(
children: [
Container(
width: 130,
height: 70,
child: ElevatedButton(
child: Text("Generate user value"),
onPressed:
userbtn == true ? () => generateTurn("user") : null,
),
),
SizedBox(width: 20), // Space between columns
Container(
width: 130,
height: 70,
child: ElevatedButton(
child: Text("Generate computer value"),
onPressed:
compbtn == true ? () => generateTurn("computer") : null,
),
),
SizedBox(width: 30), // Space between columns
],
),
],
),
117
),
);
}
}
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:
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.
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.
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(home: MyApp()));
}
118
class _MyAppState extends State<MyApp> {
Color currentColor = [Link];
String currentColorName = "RED";
currentColor = [Link];
currentColorName = "RED";
} else if ([Link]("GREEN") == 0) {
fgcolorRed = [Link];
fgcolorGreen = [Link];
fgcolorBlue = [Link];
currentColor = [Link];
currentColorName = "GREEN";
} else if ([Link]("BLUE") == 0) {
fgcolorRed = [Link];
fgcolorGreen = [Link];
fgcolorBlue = [Link];
currentColor = [Link];
currentColorName = "BLUE";
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
119
appBar: AppBar(title: Center(child: Text(''))),
body: Column(
mainAxisAlignment: [Link],
children: [
Row(
mainAxisAlignment: [Link],
children: [
ElevatedButton(
onPressed: () => changeColor("RED"),
style: [Link](
backgroundColor: bgcolorRed, // Background color
foregroundColor: fgcolorRed, // Text color
shape: RoundedRectangleBorder(
borderRadius: [Link](12), // Rounded
corners
side: BorderSide(
color: const [Link](255, 0, 0, 0), // Border
color
width: 1, // Border width
),
),
minimumSize: Size(80, 40),
padding: [Link](
horizontal: 16, vertical: 8), // Button padding
),
child: Text(
"RED",
style: TextStyle(fontSize: 18),
),
),
SizedBox(width: 20), // Space between columns
ElevatedButton(
onPressed: () => changeColor("GREEN"),
style: [Link](
backgroundColor: bgcolorGreen, // Background color
foregroundColor: fgcolorGreen, // Text color
shape: RoundedRectangleBorder(
borderRadius: [Link](12), // Rounded
corners
side: BorderSide(
color: const [Link](255, 0, 0, 0), // Border
color
width: 1, // Border width
120
),
),
minimumSize: Size(80, 40),
padding: [Link](
horizontal: 16, vertical: 8), // Button padding
),
child: Text(
"GREEN",
style: TextStyle(fontSize: 18),
),
),
SizedBox(width: 20), // Space between columns
ElevatedButton(
onPressed: () => changeColor("BLUE"),
style: [Link](
backgroundColor: bgcolorBlue, // Background color
foregroundColor: fgcolorBlue, // Text color
shape: RoundedRectangleBorder(
borderRadius: [Link](12), // Rounded
corners
side: BorderSide(
color: const [Link](255, 0, 0, 0), // Border
color
width: 1, // Border width
),
),
minimumSize: Size(80, 40), // Set the fixed width and
height
padding: [Link](
horizontal: 16, vertical: 8), // Button padding
),
child: Text("BLUE",
style: TextStyle(
fontWeight: [Link],
fontSize: 18,
)),
),
],
),
SizedBox(height: 20),
Container(
width: 200,
padding: [Link](8.0),
121
child: Center(
child: Text(
"$currentColorName is clicked",
style: TextStyle(color: [Link], fontSize: 20),
)),
color: currentColor)
],
),
);
}
}
Question C11*:
You need to develop a snakes and ladders game, as shown below:
122
The snakes & ladders board can be downloaded from:
[Link]
downloads/[Link]
[Link]
123
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.
[Link]
5e86e9/problem_set_solutions/[Link]
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:
Write the functions playerATurn() and playerBTurn(). Display about the winning player or
draw match.
124
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
import 'package:flutter/[Link]';
125
void main() => runApp(MyApp());
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Form Example'),
),
body: MyForm(),
),
);
}
}
@override
void dispose() {
_emailController.dispose();
_nameController.dispose();
_addressController.dispose();
[Link]();
}
@override
Widget build(BuildContext context) {
126
return Padding(
padding: const [Link](16.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
TextFormField(
controller: _emailController,
decoration:
InputDecoration(labelText: 'Email', hintText: '30 chars max'),
maxLength: 30,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your email';
}
return null;
},
),
TextFormField(
controller: _nameController,
decoration:
InputDecoration(labelText: 'Name', hintText: '50 chars max'),
maxLength: 50,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your name';
}
return null;
},
),
Text("\nGender"),
Row(
children: <Widget>[
Expanded(
child: RadioListTile<String>(
title: const Text('Male'),
value: 'Male',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
),
Expanded(
child: RadioListTile<String>(
title: const Text('Female'),
127
value: 'Female',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
),
],
),
DropdownButtonFormField<String>(
decoration: InputDecoration(labelText: 'Country'),
items: _countries.map((String country) {
return DropdownMenuItem<String>(
value: country,
child: Text(country),
);
}).toList(),
onChanged: (value) {
setState(() {
_country = value!;
});
},
validator: (value) {
if (value == null) {
return 'Please select a country';
}
return null;
},
),
Text("\nSubjects"),
Wrap(
spacing: 10.0,
runSpacing: 10.0,
children: _availableSubjects.map((subject) {
return Row(
mainAxisSize: [Link],
children: <Widget>[
Checkbox(
value: _subjects.contains(subject),
onChanged: (bool? value) {
setState(() {
if (value!) {
_subjects.add(subject);
} else {
_subjects.remove(subject);
}
128
});
},
),
Text(subject),
],
);
}).toList(),
),
Text('Skills'),
Container(
decoration: BoxDecoration(
border: [Link](),
borderRadius: [Link](5.0),
),
child: Column(
children: _availableSkills.map((skill) {
return CheckboxListTile(
title: Text(skill),
value: _skills.contains(skill),
onChanged: (bool? value) {
setState(() {
if (value!) {
_skills.add(skill);
} else {
_skills.remove(skill);
}
});
},
);
}).toList(),
),
),
TextFormField(
controller: _addressController,
decoration: InputDecoration(labelText: 'Address'),
maxLines: 3,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your address';
}
return null;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
debugPrint("HERE: ${_formKey.currentState!.validate()}");
if (_formKey.currentState!.validate()) {
129
// Handle form submission
debugPrint('Email: ${_emailController.text}');
debugPrint('Name: ${_nameController.text}');
debugPrint('Gender: $_gender');
debugPrint('Country: $_country');
debugPrint('Subjects: $_subjects');
debugPrint('Skills: $_skills');
debugPrint('Address: ${_addressController.text}');
}
},
child: Text('Submit'),
),
],
),
),
);
}
}
Question C36*:
When the application in C18 opens in tablet layout (landscape), it should be shown like this:
C++
Skills
Submit
Java
Javascript
import 'package:flutter/[Link]';
130
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Form Example'),
),
body: MyForm(),
),
);
}
}
@override
void dispose() {
_emailController.dispose();
_nameController.dispose();
_addressController.dispose();
[Link]();
131
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
bool isWideScreen = [Link] > 600;
return Padding(
padding: const [Link](16.0),
child: Form(
key: _formKey,
child: isWideScreen
? Row(
children: <Widget>[
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: 'Email',
hintText: '30 chars max'),
maxLength: 30,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your email';
}
return null;
},
),
Text("\nGender"),
Row(
children: <Widget>[
Expanded(
child: RadioListTile<String>(
title: const Text('Male'),
value: 'Male',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
),
Expanded(
132
child: RadioListTile<String>(
title: const Text('Female'),
value: 'Female',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
),
],
),
Text("\nSubjects"),
Wrap(
//spacing: 10.0,
//runSpacing: 10.0,
children: _availableSubjects.map((subject) {
return Row(
mainAxisSize: [Link],
children: <Widget>[
Checkbox(
value: _subjects.contains(subject),
onChanged: (bool? value) {
setState(() {
if (value!) {
_subjects.add(subject);
} else {
_subjects.remove(subject);
}
});
},
),
Text(subject),
],
);
}).toList(),
),
Text('Skills'),
Container(
decoration: BoxDecoration(
border: [Link](),
borderRadius: [Link](5.0),
),
child: Column(
children: _availableSkills.map((skill) {
return CheckboxListTile(
title: Text(skill),
133
value: _skills.contains(skill),
onChanged: (bool? value) {
setState(() {
if (value!) {
_skills.add(skill);
} else {
_skills.remove(skill);
}
});
},
);
}).toList(),
),
),
],
),
),
),
SizedBox(width: 16.0),
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: 'Name',
hintText: '50 chars max'),
maxLength: 50,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your name';
}
return null;
},
),
DropdownButtonFormField<String>(
decoration:
InputDecoration(labelText: 'Country'),
items: _countries.map((String country) {
return DropdownMenuItem<String>(
value: country,
child: Text(country),
);
}).toList(),
onChanged: (value) {
setState(() {
_country = value!;
134
});
},
validator: (value) {
if (value == null) {
return 'Please select a country';
}
return null;
},
),
TextFormField(
controller: _addressController,
decoration:
InputDecoration(labelText: 'Address'),
maxLines: 3,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your address';
}
return null;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Handle form submission
debugPrint(
'Email: ${_emailController.text}');
debugPrint('Name: ${_nameController.text}');
debugPrint('Gender: $_gender');
debugPrint('Country: $_country');
debugPrint('Subjects: $_subjects');
debugPrint('Skills: $_skills');
debugPrint(
'Address: ${_addressController.text}');
}
},
child: Text('Submit'),
),
],
),
135
),
),
],
)
: ListView(
children: <Widget>[
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: 'Email', hintText: '30 chars max'),
maxLength: 30,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your email';
}
return null;
},
),
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: 'Name', hintText: '50 chars max'),
maxLength: 50,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your name';
}
return null;
},
),
Text("\nGender"),
Row(
children: <Widget>[
Expanded(
child: RadioListTile<String>(
title: const Text('Male'),
value: 'Male',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
),
Expanded(
child: RadioListTile<String>(
title: const Text('Female'),
136
value: 'Female',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
),
],
),
DropdownButtonFormField<String>(
decoration: InputDecoration(labelText: 'Country'),
items: _countries.map((String country) {
return DropdownMenuItem<String>(
value: country,
child: Text(country),
);
}).toList(),
onChanged: (value) {
setState(() {
_country = value!;
});
},
validator: (value) {
if (value == null) {
return 'Please select a country';
}
return null;
},
),
Text("\nSubjects"),
Wrap(
spacing: 10.0,
runSpacing: 10.0,
children: _availableSubjects.map((subject) {
return Row(
mainAxisSize: [Link],
children: <Widget>[
Checkbox(
value: _subjects.contains(subject),
onChanged: (bool? value) {
setState(() {
if (value!) {
_subjects.add(subject);
} else {
_subjects.remove(subject);
}
});
137
},
),
Text(subject),
],
);
}).toList(),
),
Text('Skills'),
Container(
decoration: BoxDecoration(
border: [Link](),
borderRadius: [Link](5.0),
),
child: Column(
children: _availableSkills.map((skill) {
return CheckboxListTile(
title: Text(skill),
value: _skills.contains(skill),
onChanged: (bool? value) {
setState(() {
if (value!) {
_skills.add(skill);
} else {
_skills.remove(skill);
}
});
},
);
}).toList(),
),
),
TextFormField(
controller: _addressController,
decoration: InputDecoration(labelText: 'Address'),
maxLines: 3,
validator: (value) {
if (value!.isEmpty) {
return 'Please enter your address';
}
return null;
},
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Handle form submission
debugPrint('Email: ${_emailController.text}');
138
debugPrint('Name: ${_nameController.text}');
debugPrint('Gender: $_gender');
debugPrint('Country: $_country');
debugPrint('Subjects: $_subjects');
debugPrint('Skills: $_skills');
debugPrint('Address: ${_addressController.text}');
}
},
child: Text('Submit'),
),
],
),
),
);
},
);
}
}
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.
139
import 'package:flutter/[Link]';
void main() {
runApp(const MaterialApp(
home: LoginPage(),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const [Link](horizontal: 20.0),
child: Column(
crossAxisAlignment: [Link],
children: [
const SizedBox(height: 50), // Spacing from top
IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {},
),
const SizedBox(height: 20),
const Text(
140
'Login',
style: TextStyle(
fontSize: 30,
fontWeight: [Link],
),
),
const SizedBox(height: 5),
const Text(
'Please sign in to continue.',
style: TextStyle(
fontSize: 16,
color: [Link],
),
),
const SizedBox(height: 20),
_buildTextField(
context,
icon: [Link],
label: 'Email',
hintText: 'user123@[Link]',
),
const SizedBox(height: 20),
_buildPasswordField(context),
const SizedBox(height: 30),
Center(
child: ElevatedButton(
style: [Link](
backgroundColor: [Link],
padding: const [Link](
horizontal: 100, vertical: 20),
shape: RoundedRectangleBorder(
borderRadius: [Link](20),
),
),
onPressed: () {},
child: const Text(
'LOGIN',
style: TextStyle(
color: [Link],
fontSize: 16,
),
),
),
),
const SizedBox(height: 20),
Center(
child: GestureDetector(
onTap: () {
// Navigate to Sign Up page
141
[Link](
context,
MaterialPageRoute(
builder: (context) => const SignUpPage()),
);
},
child: const Text(
"Don't have an account? Sign up",
style: TextStyle(
color: [Link],
fontSize: 16,
),
),
),
),
],
),
),
),
);
}
142
labelText: 'Password',
enabledBorder: const UnderlineInputBorder(
borderSide: BorderSide(color: [Link]),
),
focusedBorder: OutlineInputBorder(
borderRadius: [Link](10),
borderSide: const BorderSide(color: [Link]),
),
fillColor: [Link],
filled: true,
),
),
),
TextButton(
onPressed: () {
// Forgot password action
},
child: const Text(
'FORGOT',
style: TextStyle(
color: [Link],
fontWeight: [Link],
),
),
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const [Link](horizontal: 20.0),
child: Column(
crossAxisAlignment: [Link],
children: [
const SizedBox(height: 50), // Spacing from top
IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {},
),
const SizedBox(height: 20),
const Text(
'Create Account',
143
style: TextStyle(
fontSize: 30,
fontWeight: [Link],
),
),
const SizedBox(height: 20),
_buildTextField(
context,
icon: [Link],
label: 'Full Name',
),
const SizedBox(height: 20),
_buildTextField(
context,
icon: [Link],
label: 'Email',
),
const SizedBox(height: 20),
_buildTextField(
context,
icon: [Link],
label: 'Password',
obscureText: true,
),
const SizedBox(height: 20),
_buildTextField(
context,
icon: [Link],
label: 'Confirm Password',
obscureText: true,
),
const SizedBox(height: 30),
Center(
child: ElevatedButton(
style: [Link](
backgroundColor: [Link],
padding: const [Link](
horizontal: 100, vertical: 20),
shape: RoundedRectangleBorder(
borderRadius: [Link](20),
),
),
onPressed: () {},
child: const Text(
'SIGN UP',
style: TextStyle(
color: [Link],
fontSize: 16,
),
),
144
),
),
const SizedBox(height: 20),
Center(
child: GestureDetector(
onTap: () {
// Navigate to Sign In page
[Link](
context,
MaterialPageRoute(
builder: (context) => const LoginPage()),
);
},
child: const Text(
'Already have an account? Sign in',
style: TextStyle(
color: [Link],
fontSize: 16,
),
),
),
),
],
),
),
),
);
}
145
Question C40:
E-mail Name
Country City
Address
SUBMIT
When the screen size is reduced, the layout should be changed to:
Name
Country
City
Address
SUBMIT
146
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Responsive Form')),
body: const ResponsiveForm(),
),
);
}
}
@override
_ResponsiveFormState createState() => _ResponsiveFormState();
}
void _submit() {
debugPrint('E-mail: ${[Link]}');
debugPrint('Name: ${[Link]}');
debugPrint('Country: ${[Link]}');
debugPrint('City: ${[Link]}');
debugPrint('Address: ${[Link]}');
}
@override
void dispose() {
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
147
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if ([Link] > 600) {
// Tablet (landscape) layout
return Padding(
padding: const [Link](16.0),
child: [Link](
crossAxisCount: 2,
crossAxisSpacing: 16.0,
mainAxisSpacing: 16.0,
childAspectRatio: 4.0,
children: [
TextField(
controller: emailController,
decoration: const InputDecoration(labelText: 'E-mail'),
),
TextField(
controller: nameController,
decoration: const InputDecoration(labelText: 'Name'),
),
TextField(
controller: countryController,
decoration: const InputDecoration(labelText: 'Country'),
),
TextField(
controller: cityController,
decoration: const InputDecoration(labelText: 'City'),
),
TextField(
controller: addressController,
decoration: const InputDecoration(labelText: 'Address'),
maxLines: 3,
),
const SizedBox(), // Empty space to balance the grid
ElevatedButton(
onPressed: _submit,
child: const Text('SUBMIT'),
),
],
),
);
} else {
// Phone (portrait) layout
return Padding(
padding: const [Link](16.0),
child: SingleChildScrollView(
148
child: Column(
crossAxisAlignment: [Link],
children: [
TextField(
controller: emailController,
decoration: const InputDecoration(labelText: 'E-mail'),
),
const SizedBox(height: 16.0),
TextField(
controller: nameController,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 16.0),
TextField(
controller: countryController,
decoration: const InputDecoration(labelText: 'Country'),
),
const SizedBox(height: 16.0),
TextField(
controller: cityController,
decoration: const InputDecoration(labelText: 'City'),
),
const SizedBox(height: 16.0),
TextField(
controller: addressController,
decoration: const InputDecoration(labelText: 'Address'),
maxLines: 3,
),
const SizedBox(height: 16.0),
ElevatedButton(
onPressed: _submit,
child: const Text('SUBMIT'),
),
],
),
),
);
}
},
);
}
}
Question C12*:
The following is the website view of Standford university’s computer science
department.
149
You need to re-design the above view in mobile layout as follows:
You may need to use scrolling.
150
151
import 'package:flutter/[Link]';
void main() {
runApp(const StanfordApp());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: StanfordHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Stanford University',
style: TextStyle(color: [Link]),
),
backgroundColor: const [Link](255, 109, 1, 1),
actions: [
TextButton(
onPressed: () {},
child: TextButton(
onPressed: () {},
child: const Text('CSID Login',
style: TextStyle(color: [Link])),
),
),
],
),
body: SingleChildScrollView(
child:
Column(crossAxisAlignment: [Link], children: [
const BannerText(),
const MenuAndSearchBar(),
const SliderScreen(),
Padding(
padding: const [Link](16.0),
152
child: Column(
crossAxisAlignment: [Link],
children: [
const SectionHeading(heading: "News"),
const SizedBox(height: 20),
_buildNewsSection(),
const SizedBox(height: 16),
const SectionHeading(heading: "Events"),
const SizedBox(height: 16),
_buildEventsSection(),
])),
Container(
height: 20,
color: const [Link](255, 233, 236, 221),
),
Padding(
padding: const [Link](16.0),
child: Column(
crossAxisAlignment: [Link],
children: [
const SizedBox(height: 16),
_buildContactInfoSection(),
])),
Container(
height: 40,
color: [Link][900]!,
),
Container(
height: 15,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: [Link],
end: [Link],
colors: [
const [Link](255, 160, 28, 28)!,
[Link][900]!,
],
))),
const FooterNavigation(),
]),
),
drawer: const MakeMenuItems(),
);
}
Widget _buildNewsSection() {
return Column(
crossAxisAlignment: [Link],
children: [
_buildNewsItem(
'[Link] // Placeholder image URL
153
'THURSDAY, FEBRUARY 25, 2021',
'John Hennessy honored for inventing the chip architecture behind computing',
'Stanford’s President Emeritus and collaborator David Patterson share the BBVA
Foundation Frontiers of Knowledge Award for this feat, and for co-authoring a textbook to
train chip engineers.',
),
const SizedBox(height: 25),
_buildNewsItem(
'[Link] // Placeholder image URL
'TUESDAY, FEBRUARY 9, 2021',
'Once incarcerated, a transfer student forges a new path at Stanford',
'Jason Spyres, who began his university studies as a transfer student in 2018, set
his sights on the Farm after hearing an inspiring talk by a Stanford admission officer.',
),
TextButton(
onPressed: () {},
style: [Link](padding: [Link]),
child: const Text(
"More News Stories »",
style: TextStyle(
fontStyle: [Link], color: Color(0xE23E3E3E)),
),
),
],
);
}
Widget _buildNewsItem(
String imageUrl, String date, String title, String description) {
return Column(
crossAxisAlignment: [Link],
children: [
Row(
crossAxisAlignment: [Link],
children: [
Container(
color: const [Link](255, 176, 176, 176),
padding: const [Link](4),
child: [Link](
imageUrl, // Placeholder image URL
width: 100,
height: 100,
fit: [Link],
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: [Link],
children: [
Text(
154
date,
style: const TextStyle(
fontWeight: [Link],
fontSize: 14,
),
),
const SizedBox(height: 8),
Text(
title,
style: const TextStyle(
fontWeight: [Link],
fontSize: 16,
color: [Link](255, 142, 0, 0),
),
),
const SizedBox(height: 8),
],
),
),
],
),
const SizedBox(height: 8),
Text(
description,
style: const TextStyle(
fontSize: 14, color: [Link](255, 37, 37, 37)),
),
],
);
}
Widget _buildEventsSection() {
return Column(
crossAxisAlignment: [Link],
children: [
const SizedBox(height: 8),
_buildEventItem('SUNDAY, JANUARY 2', 'Stanford Winter Closure Ends',
'12:00 am to 11:45 pm'),
_buildEventItem('MONDAY, JANUARY 3', 'First Day of Winter Quarter',
'12:00 am to 11:45 pm'),
_buildEventItem(
'WEDNESDAY, JANUARY 12',
'ETL: Sara Menker, Founder and CEO, Gro Intelligence, Hans Tung, Managing
Partner, GGV Capital',
'4:00 pm to 5:00 pm'),
TextButton(
onPressed: () {},
style: [Link](padding: [Link]),
child: const Text(
"More Events »",
style: TextStyle(
155
fontStyle: [Link], color: Color(0xE23E3E3E)),
),
),
],
);
}
Widget _buildContactInfoSection() {
return Column(
crossAxisAlignment: [Link],
children: [
const Text(
'Gates Computer Science Building\n353 Jane Stanford Way\nStanford, CA 94305',
style: TextStyle(fontSize: 16),
),
const SizedBox(height: 8),
const Text('Phone: (650) 723-2300', style: TextStyle(fontSize: 16)),
const SizedBox(height: 8),
const Text('Admissions :', style: TextStyle(fontSize: 16)),
const Text('admissions@[Link]',
style:
TextStyle(fontSize: 16, color: [Link](255, 110, 7, 0))),
TextButton(
onPressed: () {},
style: [Link](padding: [Link]),
child: const Text('Campus Map »'),
),
],
);
}
}
156
@override
State<SliderScreen> createState() => _SliderScreenState();
}
void _previousImage() {
setState(() {
_currentIndex = (_currentIndex - 1) % _images.length;
});
}
void _nextImage() {
setState(() {
_currentIndex = (_currentIndex + 1) % _images.length;
});
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const [Link](horizontal: 10),
child: Column(
mainAxisSize: [Link],
children: [
Container(
color: const [Link](255, 225, 225, 225),
padding: const [Link](8),
child: Stack(
children: [
[Link](
_images[_currentIndex],
width: 400,
height: 200,
fit: [Link],
),
Positioned(
left: 10,
top: 75,
child: CircleAvatar(
backgroundColor: Colors.black54,
child: IconButton(
icon: const Icon(Icons.arrow_back, color: [Link]),
onPressed: _previousImage,
157
),
),
),
Positioned(
right: 10,
top: 75,
child: CircleAvatar(
backgroundColor: Colors.black54,
child: IconButton(
icon:
const Icon(Icons.arrow_forward, color: [Link]),
onPressed: _nextImage,
),
),
),
],
),
),
Container(
color: const [Link](255, 225, 225, 225),
padding: const [Link](8),
child: const Padding(
padding: [Link](horizontal: 8),
child: Text(
'Pat Hanrahan: “Curiosity and passion determine success”',
style: TextStyle(
color: [Link](255, 107, 0, 0),
fontSize: 18,
),
textAlign: [Link],
),
)),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: [Link],
children: <Widget>[
Text(
heading,
style: const TextStyle(
fontSize: 40,
158
color: [Link],
),
),
Container(
height: 1,
color: [Link][400],
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Container(
color: [Link][800],
child: Padding(
padding: const [Link](16.0),
child: Column(
mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: <Widget>[
const Text(
'Stanford',
style: TextStyle(
fontSize: 32,
color: [Link],
fontWeight: [Link],
fontFamily: "Times"),
textAlign: [Link],
),
const Text(
'University',
style: TextStyle(
fontSize: 24,
color: [Link],
fontWeight: [Link],
fontFamily: "Times"),
textAlign: [Link],
),
const SizedBox(height: 16),
Row(
mainAxisAlignment: [Link],
crossAxisAlignment: [Link],
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: [Link],
159
children: [
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Stanford Home',
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Maps & Directions',
style: TextStyle(color: [Link], fontSize: 20),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Search',
style: TextStyle(color: [Link], fontSize: 20),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Stanford',
style: TextStyle(color: [Link], fontSize: 20),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Emergency Info',
style: TextStyle(color: [Link], fontSize: 20),
),
),
],
)),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: [Link],
children: [
160
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Terms of Use',
style: TextStyle(color: [Link], fontSize: 20),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Copyright',
style: TextStyle(color: [Link], fontSize: 20),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Trademarks',
style: TextStyle(color: [Link], fontSize: 20),
),
),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Non-Discrimination',
style: TextStyle(color: [Link], fontSize: 20),
)),
TextButton(
onPressed: () {},
style: [Link](),
child: const Text(
'Accessibility',
style: TextStyle(color: [Link], fontSize: 20),
),
),
],
),
),
],
),
const SizedBox(height: 16),
const Text(
'© Stanford University, Stanford, California 94305.',
style: TextStyle(
color: [Link],
fontSize: 16,
),
161
textAlign: [Link],
),
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
return const Padding(
padding: [Link](16.0),
child: Column(
crossAxisAlignment: [Link],
children: [
Text(
'Stanford',
style: TextStyle(
color: [Link],
fontSize: 32,
fontWeight: [Link],
),
),
Text(
'ENGINEERING',
style: TextStyle(
color: [Link],
fontSize: 28,
fontWeight: [Link],
),
),
Text(
'Computer Science',
style: TextStyle(
color: Colors.black54,
fontSize: 24,
),
),
],
),
);
}
}
162
@override
Widget build(BuildContext context) {
return Container(
color: const [Link](255, 24, 24, 24),
child: Padding(
padding: const [Link](8.0),
child: Row(
children: [
Builder(builder: (context) {
return Padding(
padding: const [Link](4.0),
child: Container(
color: Colors
.red[900], // Maroon background color for drawer icon
child: IconButton(
icon: const Icon([Link], color: [Link]),
onPressed: () {
[Link](context).openDrawer();
},
),
),
);
}),
const Spacer(),
Expanded(
flex: 4,
child: Container(
decoration: BoxDecoration(
color: [Link][300], // Cream color background
borderRadius: const [Link](
topLeft: [Link](5),
bottomLeft: [Link](5),
),
),
child: const TextField(
decoration: InputDecoration(
hintText: 'Search this site...',
hintStyle: TextStyle(color: Colors.black54),
border: [Link],
contentPadding: [Link](horizontal: 10),
),
style: TextStyle(color: [Link]),
),
),
),
Expanded(
flex: 1,
child: Container(
decoration: BoxDecoration(
color: [Link][300], // Cream color background
borderRadius: const [Link](
163
topRight: [Link](5),
bottomRight: [Link](5),
),
),
child: IconButton(
icon: const Icon([Link], color: [Link]),
onPressed: () {
// Perform search action
},
),
),
),
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
padding: [Link],
children: <Widget>[
const DrawerHeader(
decoration: BoxDecoration(
color: [Link],
),
child: Text(
'Drawer Header',
style: TextStyle(
color: [Link],
fontSize: 24,
),
),
),
ListTile(
leading: const Icon([Link]),
title: const Text('Home'),
onTap: () {
// Navigate to home
[Link](context);
},
),
ListTile(
leading: const Icon([Link]),
title: const Text('Settings'),
164
onTap: () {
// Navigate to settings
[Link](context);
},
),
],
),
);
}
}
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 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.
*/
import 'package:flutter/[Link]';
void main() {
runApp(
const MaterialApp(title: 'Passing Data', home: HomeScreen()),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Send Data'),
),
body: Center(
child: Column(
mainAxisAlignment: [Link],
165
children: [
ElevatedButton(
onPressed: () {
Map<String, dynamic> data = {"num1": 10, "num2": 20};
[Link](
context,
MaterialPageRoute(
builder: (context) => const DataReceiver(),
settings: RouteSettings(arguments: data),
),
);
},
child: const Text('Send'),
),
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
final args = [Link](context)!.[Link] as Map;
return Scaffold(
appBar: AppBar(
title: const Text('Received Data'),
),
body: Center(
child: Text(
"Number 1: ${args['num1']}\nNumber 2: ${args['num2']}",
style: const TextStyle(fontSize: 20.0),
),
),
);
}
}
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
166
screen (using RouteSettings) where they are simply displayed. You need to write the
widgets of homescreen and profilescreen.
Submit Back
import 'package:flutter/[Link]';
void main() {
runApp(const MaterialApp(home: HomeScreen()));
}
@override
State<HomeScreen> createState() => _HomeScreenState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('HOME SCREEN')),
),
body: Column(
children: [
Row(
children: [
const Expanded(
child: Padding(
padding: [Link](left: 50),
child: Text('E-mail'),
),
),
SizedBox(
width: 240,
167
child: Padding(
padding: const [Link](right: 50),
child: SizedBox(
child: TextField(
controller: _email,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding: [Link](
vertical: 0.0, horizontal: 10.0),
),
),
),
),
)
],
),
const SizedBox(height: 20),
Row(
children: [
const Expanded(
child: Padding(
padding: [Link](left: 50),
child: Text('Person Name'),
),
),
SizedBox(
width: 240,
child: Padding(
padding: const [Link](right: 50),
child: SizedBox(
child: TextField(
controller: _name,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding: [Link](
vertical: 0.0, horizontal: 10.0),
),
),
),
),
)
],
),
Row(
children: [
Expanded(
child: Padding(
padding: const [Link](top: 10, left: 80, right: 80),
child: ElevatedButton(
onPressed: () {
168
Map<String, dynamic> data = {
"email": _email.text,
"name": _name.text
};
[Link](
context,
MaterialPageRoute(
builder: (context) => const ProfileScreen(),
settings: RouteSettings(arguments: data),
),
);
},
child: const Text('SUBMIT'),
),
),
),
],
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
final args = [Link](context)!.[Link] as Map;
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('PROFILE SCREEN')),
),
body: Column(
children: [
Row(
children: [
const Expanded(
child: Padding(
padding: [Link](left: 50),
child: Text('E-mail'),
),
),
SizedBox(
width: 240,
child: Padding(
padding: const [Link](right: 50),
169
child: SizedBox(
child: Text(args["email"],
style: const TextStyle(fontStyle: [Link])),
),
),
)
],
),
const SizedBox(height: 20),
Row(
children: [
const Expanded(
child: Padding(
padding: [Link](left: 50),
child: Text('Person Name'),
),
),
SizedBox(
width: 240,
child: Padding(
padding: const [Link](right: 50),
child: SizedBox(
child: Text(args["name"],
style: const TextStyle(fontStyle: [Link])),
),
),
)
],
),
],
),
);
}
}
Question A12:
0 The value is 33
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
170
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.
import 'dart:math';
import 'package:flutter/[Link]';
void main() {
runApp(const MaterialApp(home: HomeScreen()));
}
@override
State<HomeScreen> createState() => _HomeScreenState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('HOME SCREEN')),
),
body: Column(
children: [
SizedBox(
width: 240,
child: Padding(
padding: const [Link](right: 0, left: 0),
child: SizedBox(
171
child: TextField(
controller: _controller,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding:
[Link](vertical: 0.0, horizontal: 10.0),
),
),
),
),
),
const SizedBox(height: 20),
Row(
children: [
Expanded(
child: Padding(
padding: const [Link](top: 0, left: 10, right: 0),
child: ElevatedButton(
onPressed: () => updateTextBox("RANDOM"),
child: const Text('RANDOM'),
),
),
),
Expanded(
child: Padding(
padding: const [Link](top: 0, left: 10, right: 0),
child: ElevatedButton(
onPressed: () => updateTextBox("COUNTER"),
child: const Text('COUNTER'),
),
),
),
Expanded(
child: Padding(
padding: const [Link](top: 0, left: 10, right: 10),
child: ElevatedButton(
onPressed: () {
Map<String, dynamic> data = {"value": _controller.text};
[Link](
context,
MaterialPageRoute(
builder: (context) => const Display(),
settings: RouteSettings(arguments: data),
),
);
},
child: const Text('SEND'),
),
),
),
172
],
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
final args = [Link](context)!.[Link] as Map;
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('DISPLAY SCREEN')),
),
body: Column(
children: [
SizedBox(
width: 300,
child: Padding(
padding: const [Link](right: 50, left: 50),
child: SizedBox(
child: Text("The value is: ${args["value"]}"),
),
),
),
],
),
);
}
}
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.
173
Home Display
Abbottabad
CLICK
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(home: HomeScreen()));
}
HomeScreen({[Link]});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('HOME')),
),
body: Column(
children: [
SizedBox(
width: 400,
child: Padding(
padding: const [Link](left: 50, right: 50),
child: SizedBox(
child: TextField(
controller: _city,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding:
[Link](vertical: 0.0, horizontal: 10.0),
),
),
),
),
),
const SizedBox(height: 20),
SizedBox(
174
width: 400,
child: Padding(
padding: const [Link](left: 50, right: 50),
child: SizedBox(
child: TextField(
controller: _country,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding:
[Link](vertical: 0.0, horizontal: 10.0),
),
),
),
),
),
Padding(
padding: const [Link](top: 10, left: 80, right: 80),
child: ElevatedButton(
onPressed: () {
Map<String, dynamic> data = {
"city": _city.text,
"country": _country.text
};
[Link](
context,
MaterialPageRoute(
builder: (context) => const DisplayScreen(),
settings: RouteSettings(arguments: data),
),
);
},
child: const Text('SUBMIT'),
),
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
final args = [Link](context)!.[Link] as Map;
return Scaffold(
appBar: AppBar(
175
title: const Center(child: Text('DISPLAY')),
),
body: Column(
children: [
Row(
children: [
Expanded(
child: Padding(
padding: const [Link](left: 50, right: 50),
child: Container(
decoration: BoxDecoration(border: [Link](width: 1)),
child: Padding(
padding: const [Link](
10), // Adjust the padding value as needed
child: Text("${args["city"]}, ${args["country"]}"),
),
),
),
),
],
),
],
),
);
}
}
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
176
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(home: HomeScreen()));
}
HomeScreen({[Link]});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('HOME')),
),
body: Column(
children: [
SizedBox(
width: 400,
child: Padding(
padding: const [Link](left: 50, right: 50),
child: SizedBox(
child: TextField(
controller: _num,
decoration: const InputDecoration(
border: OutlineInputBorder(),
contentPadding:
[Link](vertical: 0.0, horizontal: 10.0),
),
),
),
),
),
Padding(
padding: const [Link](top: 10, left: 80, right: 80),
child: ElevatedButton(
onPressed: () {
Map<String, dynamic> data = {
"num": _num.text,
};
[Link](
context,
MaterialPageRoute(
builder: (context) => const DisplayScreen(),
settings: RouteSettings(arguments: data),
),
);
177
},
child: const Text('SUBMIT'),
),
),
],
),
);
}
}
@override
Widget build(BuildContext context) {
final args = [Link](context)!.[Link] as Map;
int num = 0;
String result = "";
if ([Link](args["num"]) != null) {
num = [Link](args["num"]);
if (num == 1) {
result = "Received number is one";
} else if (num == 2) {
result = "Received number is two";
} else if (num == 3) {
result = "Received number is three";
} else {
result = "Invalid number";
}
} else {
result = "Invalid number";
}
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('DISPLAY')),
),
body: Column(
children: [
Row(
children: [
Expanded(
child: Padding(
padding: const [Link](left: 50, right: 50),
child: Container(
decoration: BoxDecoration(border: [Link](width: 1)),
child: Padding(
padding: const [Link](
178
10), // Adjust the padding value as needed
child: Text(result),
),
),
),
),
],
),
],
),
);
}
}
Question A23:
Use Flutter Widgets to design following screens:
Home screen
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:
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 [Link].
Each subcategory page should have back navigation button and a button to navigate directly to
the home screen.
179
Please make beautiful interfaces, some samples are attached, but you can find more on
[Link].
180
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: [Link](
seedColor: const [Link](255, 178, 163, 203)),
cardTheme: const CardTheme(color: [Link](255, 255, 254, 250)),
useMaterial3: true,
),
home: HomePage(),
));
}
181
Category('Flash Drives', '[Link]
Category('Solid State Drives', '[Link]
Category('Keyboards', '[Link]
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Products'),
),
body: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
final cat = cats[index];
return Padding(
padding: const [Link](8.0),
child: Card(
elevation: 3, // Adjust the elevation value as needed
shape: RoundedRectangleBorder(
borderRadius: [Link](10),
),
child: Container(
decoration: BoxDecoration(
color: [Link].shade50,
borderRadius: [Link](10),
),
child: ListTile(
leading:
[Link]([Link], width: 40, height: 40),
title: Text([Link]),
onTap: () {
[Link](
context,
MaterialPageRoute(
builder: (context) =>
Products(productCategory: [Link]),
),
);
},
),
),
),
);
},
),
);
}
}
182
class DetailPage extends StatelessWidget {
final Product product;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text([Link]),
),
body: Padding(
padding: const [Link](16.0),
child: Card(
elevation: 4,
child: Padding(
padding: const [Link](16.0),
child: Column(
mainAxisSize: [Link],
children: [
[Link](
[Link],
width: 200,
height: 200,
fit: [Link],
),
const SizedBox(height: 16),
Text(
[Link],
style: const TextStyle(
fontSize: 24, fontWeight: [Link]),
),
Text("Price: ${[Link]}"),
const SizedBox(height: 12),
Text([Link]),
ElevatedButton(
onPressed: () {},
style: [Link](
elevation: 4,
backgroundColor: const [Link](
255, 104, 185, 251), // Background color
foregroundColor: [Link], // Text color
),
child: const Text("Add to Cart"),
)
],
),
),
)));
}
183
}
class Category {
final String name;
final String thumbnailUrl;
Category([Link], [Link]);
}
class Product {
final String name;
final String thumbnailUrl;
final double price;
final String specs;
Product(
{required [Link],
required [Link],
required [Link],
required [Link]});
}
184
),
Product(
name: 'HP Notebook',
thumbnailUrl: '[Link]
price: 3249.99,
specs:
"Core i9 Processor, 300 GB SSD, Intel Graphics Card, 15.1 inch screen
size",
),
Product(
name: 'Acer Max',
thumbnailUrl: '[Link]
price: 249.99,
specs:
"Core i9 Processor, 300 GB SSD, Intel Graphics Card, 15.1 inch screen
size",
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(productCategory),
),
body: Padding(
padding: const [Link](20.0), // Padding around the grid
child: [Link](
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3, // Number of columns
childAspectRatio: 0.6, // Aspect ratio of the grid items
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
),
itemCount: [Link],
itemBuilder: (BuildContext context, int index) {
final product = products[index];
return GestureDetector(
onTap: () {
// Navigate to product detail page
[Link](
context,
MaterialPageRoute(
builder: (context) => DetailPage(product: product),
),
);
},
child: Container(
padding: const [Link](8),
decoration: BoxDecoration(
185
color: const [Link](255, 254, 255, 251),
borderRadius: [Link](10),
boxShadow: const [
BoxShadow(
blurStyle: [Link],
blurRadius: 3,
color: [Link])
]),
Question A24:
Create an app with 4 screens, and use Tab navigation to navigate between screens
import 'package:flutter/[Link]';
void main() {
runApp(const MaterialApp(home: TabBarDemo()));
186
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 4,
child: Scaffold(
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.directions_car)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_bike)),
Tab(icon: Icon(Icons.directions_boat)),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
MyScreen(item: "Car"),
MyScreen(item: "Bus"),
MyScreen(item: "Cycle"),
MyScreen(item: "Boat")
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
return Text(item);
}
}
Question A26:
187
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.
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: BannerScreen(),
debugShowCheckedModeBanner: false,
);
}
}
@override
_BannerScreenState createState() => _BannerScreenState();
}
void _toggleSignIn() {
setState(() {
_isSignedIn = !_isSignedIn;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 80,
backgroundColor: [Link],
title: Row(
children: [
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: 'Search...',
188
fillColor: [Link],
filled: true,
contentPadding: const [Link](
vertical: 10.0, horizontal: 15.0),
border: OutlineInputBorder(
borderRadius: [Link](25.0),
borderSide: [Link],
),
),
),
),
const SizedBox(width: 10.0),
ElevatedButton(
onPressed: () {
// Perform search action
},
style: [Link](
backgroundColor: [Link],
shape: RoundedRectangleBorder(
borderRadius: [Link](20.0),
),
padding: const [Link](horizontal: 20.0),
),
child: const Text('Search'),
),
const SizedBox(width: 10.0),
ElevatedButton(
onPressed: _toggleSignIn,
style: [Link](
backgroundColor: _isSignedIn ? [Link] : [Link],
shape: RoundedRectangleBorder(
borderRadius: [Link](20.0),
),
padding: const [Link](horizontal: 20.0),
),
child: Text(_isSignedIn ? 'Sign Out' : 'Sign In'),
),
],
),
),
body: const Center(
child: Text('Content goes here'),
),
);
}
}
Question A27:
189
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
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MainTabs(),
);
}
}
@override
State<MainTabs> createState() => _MainTabsState();
}
@override
void initState() {
[Link]();
_mainTabController = TabController(length: 2, vsync: this);
}
@override
void dispose() {
_mainTabController.dispose();
[Link]();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Main Tabs'),
bottom: TabBar(
190
controller: _mainTabController,
tabs: const [
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
],
),
),
body: TabBarView(
controller: _mainTabController,
children: const [
Tab1(),
Tab2(),
],
),
);
}
}
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
bottom: const TabBar(
tabs: [
Tab(text: 'Screen 1'),
Tab(text: 'Screen 2'),
],
),
),
body: const TabBarView(
children: [
Screen1(),
Screen2(),
],
),
),
);
}
}
@override
191
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
bottom: const TabBar(
tabs: [
Tab(text: 'Screen 3'),
Tab(text: 'Screen 4'),
],
),
),
body: const TabBarView(
children: [
Screen3(),
Screen4(),
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 1'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 2'),
);
}
}
@override
192
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 3'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 4'),
);
}
}
Question A28:
Create an app with 4 screens, and use Drawer navigation to navigate between
screens
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
@override
State<HomeScreen> createState() => _HomeScreenState();
}
193
int _selectedDrawerIndex = 0;
_getDrawerItemWidget(int pos) {
switch (pos) {
case 0:
return const Screen1();
case 1:
return const Screen2();
case 2:
return const Screen3();
case 3:
return const Screen4();
default:
return const Center(child: Text("Error"));
}
}
_onSelectItem(int index) {
setState(() {
_selectedDrawerIndex = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Drawer Navigation'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(
child: Text(
'Navigation Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
ListTile(
title: const Text('Screen 1'),
selected: _selectedDrawerIndex == 0,
onTap: () => _onSelectItem(0),
),
ListTile(
title: const Text('Screen 2'),
selected: _selectedDrawerIndex == 1,
194
onTap: () => _onSelectItem(1),
),
ListTile(
title: const Text('Screen 3'),
selected: _selectedDrawerIndex == 2,
onTap: () => _onSelectItem(2),
),
ListTile(
title: const Text('Screen 4'),
selected: _selectedDrawerIndex == 3,
onTap: () => _onSelectItem(3),
),
],
),
),
body: _getDrawerItemWidget(_selectedDrawerIndex),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 1'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 2'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 3'),
);
195
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 4'),
);
}
}
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
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MainDrawer(),
);
}
}
@override
State<MainDrawer> createState() => _MainDrawerState();
}
196
_getDrawerContent(int pos) {
switch (pos) {
case 0:
return const Drawer1();
case 1:
return const Drawer2();
default:
return const Center(child: Text("Error"));
}
}
_onSelectMainDrawer(int index) {
setState(() {
_selectedDrawer = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Main Drawer Navigation'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(
child: Text(
'Main Navigation Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
ListTile(
title: const Text('Drawer 1'),
selected: _selectedDrawer == 0,
onTap: () => _onSelectMainDrawer(0),
),
ListTile(
title: const Text('Drawer 2'),
selected: _selectedDrawer == 1,
onTap: () => _onSelectMainDrawer(1),
),
],
),
),
body: _getDrawerContent(_selectedDrawer),
197
);
}
}
@override
State<Drawer1> createState() => _Drawer1State();
}
_getDrawer1ItemWidget(int pos) {
switch (pos) {
case 0:
return const Screen1();
case 1:
return const Screen2();
default:
return const Center(child: Text("Error"));
}
}
_onSelectDrawer1Item(int index) {
setState(() {
_selectedDrawerIndex = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Drawer 1'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(
child: Text(
'Drawer 1 Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
198
ListTile(
title: const Text('Screen 1'),
selected: _selectedDrawerIndex == 0,
onTap: () => _onSelectDrawer1Item(0),
),
ListTile(
title: const Text('Screen 2'),
selected: _selectedDrawerIndex == 1,
onTap: () => _onSelectDrawer1Item(1),
),
],
),
),
body: _getDrawer1ItemWidget(_selectedDrawerIndex),
);
}
}
@override
State<Drawer2> createState() => _Drawer2State();
}
_getDrawer2ItemWidget(int pos) {
switch (pos) {
case 0:
return const Screen3();
case 1:
return const Screen4();
default:
return const Center(child: Text("Error"));
}
}
_onSelectDrawer2Item(int index) {
setState(() {
_selectedDrawerIndex = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
199
title: const Text('Drawer 2'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(
child: Text(
'Drawer 2 Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
ListTile(
title: const Text('Screen 3'),
selected: _selectedDrawerIndex == 0,
onTap: () => _onSelectDrawer2Item(0),
),
ListTile(
title: const Text('Screen 4'),
selected: _selectedDrawerIndex == 1,
onTap: () => _onSelectDrawer2Item(1),
),
],
),
),
body: _getDrawer2ItemWidget(_selectedDrawerIndex),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 1'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 2'),
200
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 3'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 4'),
);
}
}
Question C13:
Create the following Form
When the user clicks the submit button, the data is sent to the “display screen” as shown
below.
INPUT SCREEN
201
Email
Name
Country
Backend
Database
Address
Submit
DISPLAY SCREEN
Email ali@[Link]
Country Pakistan
Gender Male
Save
import 'package:flutter/[Link]';
void main() {
runApp(const MyApp());
202
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MainDrawer(),
);
}
}
@override
State<MainDrawer> createState() => _MainDrawerState();
}
_getDrawerContent(int pos) {
switch (pos) {
case 0:
return const Drawer1();
case 1:
return const Drawer2();
default:
return const Center(child: Text("Error"));
}
}
_onSelectMainDrawer(int index) {
setState(() {
_selectedDrawer = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Main Drawer Navigation'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
203
const DrawerHeader(
child: Text(
'Main Navigation Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
ListTile(
title: const Text('Drawer 1'),
selected: _selectedDrawer == 0,
onTap: () => _onSelectMainDrawer(0),
),
ListTile(
title: const Text('Drawer 2'),
selected: _selectedDrawer == 1,
onTap: () => _onSelectMainDrawer(1),
),
],
),
),
body: _getDrawerContent(_selectedDrawer),
);
}
}
@override
State<Drawer1> createState() => _Drawer1State();
}
_getDrawer1ItemWidget(int pos) {
switch (pos) {
case 0:
return const Screen1();
case 1:
return const Screen2();
default:
return const Center(child: Text("Error"));
}
}
_onSelectDrawer1Item(int index) {
setState(() {
204
_selectedDrawerIndex = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Drawer 1'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(
child: Text(
'Drawer 1 Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
ListTile(
title: const Text('Screen 1'),
selected: _selectedDrawerIndex == 0,
onTap: () => _onSelectDrawer1Item(0),
),
ListTile(
title: const Text('Screen 2'),
selected: _selectedDrawerIndex == 1,
onTap: () => _onSelectDrawer1Item(1),
),
],
),
),
body: _getDrawer1ItemWidget(_selectedDrawerIndex),
);
}
}
@override
State<Drawer2> createState() => _Drawer2State();
}
205
_getDrawer2ItemWidget(int pos) {
switch (pos) {
case 0:
return const Screen3();
case 1:
return const Screen4();
default:
return const Center(child: Text("Error"));
}
}
_onSelectDrawer2Item(int index) {
setState(() {
_selectedDrawerIndex = index;
});
[Link](context).pop(); // close the drawer
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Drawer 2'),
),
drawer: Drawer(
child: ListView(
children: <Widget>[
const DrawerHeader(
child: Text(
'Drawer 2 Menu',
style: TextStyle(color: [Link], fontSize: 25),
),
decoration: BoxDecoration(
color: [Link],
),
),
ListTile(
title: const Text('Screen 3'),
selected: _selectedDrawerIndex == 0,
onTap: () => _onSelectDrawer2Item(0),
),
ListTile(
title: const Text('Screen 4'),
selected: _selectedDrawerIndex == 1,
onTap: () => _onSelectDrawer2Item(1),
),
],
),
),
206
body: _getDrawer2ItemWidget(_selectedDrawerIndex),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 1'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 2'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 3'),
);
}
}
@override
Widget build(BuildContext context) {
return const Center(
child: Text('Screen 4'),
);
}
}
207
Question C19:
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.
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
import 'package:provider/[Link]';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => AppState(),
child: const MyApp(),
),
);
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
208
}
@override
State<HomeScreen> createState() => _HomeScreenState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Screen'),
),
body: Padding(
padding: const [Link](16.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email'),
),
TextField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
[Link]<AppState>(context, listen: false)
.setEmail(_emailController.text);
[Link]<AppState>(context, listen: false)
.setName(_nameController.text);
[Link](
context,
MaterialPageRoute(
builder: (context) => const ProfileScreen()),
);
},
child: const Text('Submit'),
),
],
),
),
);
209
}
}
@override
Widget build(BuildContext context) {
final appState = [Link]<AppState>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Profile Screen'),
),
body: Padding(
padding: const [Link](16.0),
child: Column(
crossAxisAlignment: [Link],
children: [
Text('Email: ${[Link]}',
style: const TextStyle(fontSize: 20)),
Text('Name: ${[Link]}',
style: const TextStyle(fontSize: 20)),
ElevatedButton(
onPressed: () {
[Link]<AppState>(context, listen: false)
.setName("THIS IS UPDATED NAME");
},
child: const Text("Update Name")),
ElevatedButton(
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => const ResultScreen()),
);
},
child: const Text('Submit'),
),
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
210
final appState = [Link]<AppState>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Result Screen'),
),
body: Padding(
padding: const [Link](16.0),
child: Column(
crossAxisAlignment: [Link],
children: [
Text('Email: ${[Link]}',
style: const TextStyle(fontSize: 20)),
Text('Name: ${[Link]}',
style: const TextStyle(fontSize: 20)),
],
),
),
);
}
}
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.
Enter ID ID 25
SEARCH
NAME Osman
AGE 45
ADDRESS Abbottaba
d, Pakistan
211
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
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.
212
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.
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.
Name
Country
Backend
Database
Address
Submit
213
Use flat list or some other list to show the data of all persons, in the following format:
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).
Email ali@[Link]
Country Pakistan
Gender Male
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)
214
UPDATE DATA SCREEN
Email ali@[Link]
Update Back
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 ali@[Link]
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.
215
ID: 25
Delete
Write a method that deletes the document from firestore database whose id is 25.
import 'package:flutter/[Link]';
import 'package:flutter/[Link]';
import 'package:provider/[Link]';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => AppState(),
child: const MyApp(),
),
);
}
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomeScreen(),
);
}
}
216
_name = name;
notifyListeners();
}
}
@override
State<HomeScreen> createState() => _HomeScreenState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home Screen'),
),
body: Padding(
padding: const [Link](16.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email'),
),
TextField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
[Link]<AppState>(context, listen: false)
.setEmail(_emailController.text);
[Link]<AppState>(context, listen: false)
.setName(_nameController.text);
[Link](
context,
MaterialPageRoute(
builder: (context) => const ProfileScreen()),
);
217
},
child: const Text('Submit'),
),
],
),
),
);
}
}
@override
Widget build(BuildContext context) {
final appState = [Link]<AppState>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Profile Screen'),
),
body: Padding(
padding: const [Link](16.0),
child: Column(
crossAxisAlignment: [Link],
children: [
Text('Email: ${[Link]}',
style: const TextStyle(fontSize: 20)),
Text('Name: ${[Link]}',
style: const TextStyle(fontSize: 20)),
ElevatedButton(
onPressed: () {
[Link]<AppState>(context, listen: false)
.setName("THIS IS UPDATED NAME");
},
child: const Text("Update Name")),
ElevatedButton(
onPressed: () {
[Link](
context,
MaterialPageRoute(builder: (context) => const ResultScreen()),
);
},
child: const Text('Submit'),
),
],
218
),
),
);
}
}
@override
Widget build(BuildContext context) {
final appState = [Link]<AppState>(context);
return Scaffold(
appBar: AppBar(
title: const Text('Result Screen'),
),
body: Padding(
padding: const [Link](16.0),
child: Column(
crossAxisAlignment: [Link],
children: [
Text('Email: ${[Link]}',
style: const TextStyle(fontSize: 20)),
Text('Name: ${[Link]}',
style: const TextStyle(fontSize: 20)),
],
),
),
);
}
}
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).
219
Question C21:
We have a following layout:
Question C29:
220
Question C23:
Suppose we have the following search form:
SEARCH
Based on the search fields in the above form, create a compound query to search
record in a firestore collection “persons”.
Question C24:
You need to insert the following document in a collection name “students” in firestore
database
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
221
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
(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:
222
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.
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:
[Link]
223