0% found this document useful (0 votes)
26 views23 pages

Amad 6

The document is a comprehensive guide detailing solutions to a question bank for Flutter Unit 6, covering various topics such as configuring build.gradle for release mode, setting application labels for Android and iOS, adding custom launcher icons, and implementing splash screens. It includes specific coding examples and instructions for both Android and iOS platforms, as well as considerations for deploying Flutter apps. The guide serves as an academic and professional resource for developers working with Flutter.

Uploaded by

kevatdhwani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views23 pages

Amad 6

The document is a comprehensive guide detailing solutions to a question bank for Flutter Unit 6, covering various topics such as configuring build.gradle for release mode, setting application labels for Android and iOS, adding custom launcher icons, and implementing splash screens. It includes specific coding examples and instructions for both Android and iOS platforms, as well as considerations for deploying Flutter apps. The guide serves as an academic and professional resource for developers working with Flutter.

Uploaded by

kevatdhwani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Flutter Unit 6 Question Bank

Solutions (Detailed)

Comprehensive Academic and Professional Guide

May 10, 2025

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 1

Contents

1 Unit 6 2
1.1 How do you configure the build.gradle file for release mode in a Flutter app? 2
1.2 What is the process to set the application label (app name) in Android
and iOS? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 How can you add a custom launcher icon in a Flutter project using the
flutter_launcher_icons package? . . . . . . . . . . . . . . . . . . . . . . 4
1.4 What are the required changes in AndroidManifest.xml to reflect the new
app icon or app name? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.5 Describe the steps to implement a splash screen for both Android and iOS
in Flutter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.6 How do you customize the splash screen background color and image for
an Android Flutter app? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7 What is the difference between debug and release build modes in Flutter? 8
1.8 What command is used to generate a signed APK for Android deployment? 9
1.9 How can you generate and use a keystore for signing an Android Flutter
app? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.10 Which tools are required to publish a Flutter app on the Google Play Store? 10
1.11 What are the prerequisites for deploying a Flutter app to the Apple App
Store? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.12 How do you set up provisioning profiles and signing certificates for iOS
deployment? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.13 Explain the role of Xcode in building and publishing iOS Flutter applications. 12
1.14 What command is used to compile and generate web assets in a Flutter
web app? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.15 How do you host a Flutter web app using GitHub Pages or Firebase Hosting? 13
1.16 What files are generated in the build/web folder after building a Flutter
web app? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.17 What are the benefits and limitations of deploying a Flutter app to the web? 14

2 Programming Questions 15
2.1 Create a simple UI design to demonstrate the use of ElevatedButton and
Container Widgets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.2 Create a simple UI design to demonstrate the use of Text and Image Widgets. 16
2.3 Write a Flutter code to implement state management. (Change the states) 17
2.4 Create an app with five screens and switch between them using buttons . 18
2.5 Create a simple code to demonstrate asynchronous data loading using Fu-
tureBuilder. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.6 Write a short note on how an e-commerce app fetches product data from
an API. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 2

1 Unit 6
1.1 How do you configure the build.gradle file for release mode in a Flutter
app?
To configure the build.gradle file for release mode in a Flutter Android app, you need
to set up signing configurations and build types. This ensures the app is optimized,
signed, and ready for distribution.
1. Project-Level build.gradle (android/build.gradle):
• Ensure repositories and dependencies are set for Android builds.
• Example:
1 buildscript {
2 repositories {
3 google ()
4 mavenCentral ()
5 }
6 dependencies {
7 classpath ’ com . android . tools . build : gradle :8.1.0 ’
8 }
9 }
10 allprojects {
11 repositories {
12 google ()
13 mavenCentral ()
14 }
15 }

2. App-Level build.gradle (android/app/build.gradle):


• Add signing configurations for the release build.
• Enable minification and optimization.
• Example:
1 android {
2 compileSdkVe rsion 34
3 defaultConfig {
4 applicationId " com . example . myapp "
5 minSdkVersion 21
6 targetSdkVersion 34
7 versionCode 1
8 versionName "1.0"
9 }
10 signingConfigs {
11 release {
12 keyAlias ’ mykey ’
13 keyPassword ’ password ’
14 storeFile file ( ’ mykeystore . jks ’)
15 storePassword ’ password ’
16 }

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 3

17 }
18 buildTypes {
19 release {
20 signingConfig signingConfigs . release
21 minifyEnabled true
22 shrinkResources true
23 proguardFiles g e t D e f a u l t P r o g u a r d F i l e ( ’
proguard - android - optimize . txt ’) , ’ proguard
- rules . pro ’
24 }
25 }
26 }
27 dependencies {
28 implementation ’ androidx . core : core :1.12.0 ’
29 }

3. Key Points:
• signingConfigs: Defines the keystore for signing the APK/AAB.
• minifyEnabled: Enables code shrinking with R8.
• shrinkResources: Removes unused resources.
• proguardFiles: Applies obfuscation rules to reduce app size and protect code.
Use Case: This configuration ensures a Flutter e-commerce app is optimized (e.g., 20%
smaller) and securely signed for Google Play deployment.

1.2 What is the process to set the application label (app name) in Android
and iOS?
The application label (app name) is set differently for Android and iOS in a Flutter
project:
• Android:
1. Open android/app/src/main/AndroidManifest.xml.
2. Set the android:label attribute in the application tag:
1 < application
2 android:label = " My Flutter App "
3 android:icon = " @mipmap / ic_launcher " >

3. Alternatively, define the label in android/app/src/main/res/values/strings.xml:


1 < resources >
2 < string name = " app_name " > My Flutter App </ string >
3 </ resources >

Then reference it in AndroidManifest.xml:


1 < application
2 android:label = " @string / app_name "

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 4

3 android:icon = " @mipmap / ic_launcher " >

4. For flavors (e.g., dev, prod), define separate strings.xml files in flavor-specific
folders (e.g., android/app/src/dev/res/values/).
• iOS:
1. Open ios/Runner/Info.plist in Xcode or a text editor.
2. Update the CFBundleName key:
1 < key > CFBundleName </ key >
2 < string > My Flutter App </ string >

3. Alternatively, edit in Xcodes project settings under Target > General >
Display Name.
• Flutter-Level Consistency:
– Update pubspec.yaml to reflect the app name for consistency:
1 name : my_flutter_app
2 description : A new Flutter project .

– Ensure the name aligns with applicationId (Android) and CFBundleIdentifier


(iOS) for clarity.
Example: A fitness app sets android:label="FitTrack" and CFBundleName="FitTrack"
to ensure consistent branding across platforms.

1.3 How can you add a custom launcher icon in a Flutter project using the
flutter_launcher_icons package?
The flutter_launcher_icons package automates generating launcher icons for Android
and iOS.
1. Add Dependency:
• In pubspec.yaml:
1 dev_dependencies :
2 flu tt er _ la u n c h e r _ i c o n s : ^0.13.1

• Run flutter pub get.


2. Prepare Icon Image:
• Create a high-resolution icon (e.g., 1024x1024 PNG) and place it in assets/icon/icon.png.
3. Configure pubspec.yaml:
1 f lu tt er _la un ch e r _ i c o n s :
2 android : true
3 ios : true
4 image_path : " assets / icon / icon . png "
5 ad a p t iv e _ i co n _ b a c k g r o u n d : "# FFFFFF "
6 ad a p t iv e _ i co n _ f o r e g r o u n d : " assets / icon / icon . png "

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 5

• android: true: Generates Android icons (mipmap).


• ios: true: Generates iOS icons (AppIcon.appiconset).
• adaptive_icon_background: Sets Android adaptive icon background (color
or image).
4. Generate Icons:
• Run:
1 flutter pub run f l u t t e r _ l a u n c h e r _ i c o n s

• This updates android/app/src/main/res/mipmap-* for Android and ios/Runner/Assets.x


for iOS.
5. Verify:
• Check AndroidManifest.xml references android:icon="@mipmap/ic_launcher".
• In Xcode, verify the iOS icon in Assets.xcassets.
Example: A travel app uses flutter_launcher_icons to generate a branded icon, en-
suring sharp visuals on Android (adaptive) and iOS (retina) devices.

1.4 What are the required changes in AndroidManifest.xml to reflect the


new app icon or app name?
To update the app icon or name in android/app/src/main/AndroidManifest.xml:
1. App Name:
• Modify the android:label in the application tag:
1 < application
2 android:label = " New App Name "
3 android:icon = " @mipmap / ic_launcher " >

• Or reference a string resource:


1 < application
2 android:label = " @string / app_name "
3 android:icon = " @mipmap / ic_launcher " >

Update android/app/src/main/res/values/strings.xml:
1 < string name = " app_name " > New App Name </ string >

2. App Icon:
• Ensure android:icon points to the correct mipmap resource:
1 < application
2 android:label = " New App Name "
3 android:icon = " @mipmap / ic_launcher " >

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 6

• After generating icons (e.g., via flutter_launcher_icons), verify that mipmap-*


folders in android/app/src/main/res/ contain the new icons.
3. Activity-Level Consistency:
• Update the android:label in the activity tag if a different launcher name
is needed:
1 < activity
2 android:name = " . MainActivity "
3 android:label = " New App Name " >

Example: A news app updates android:label="NewsNow" and ensures android:icon="@mipmap/ic_la


reflects the new logo generated by flutter_launcher_icons.

1.5 Describe the steps to implement a splash screen for both Android and
iOS in Flutter.
A splash screen displays a logo or branding during app launch. Flutter supports native
splash screens for Android and iOS using the flutter_native_splash package.
1. Add Dependency:
1 dev_dependencies :
2 flut t er_n at iv e _ s p l a s h : ^2.4.0

Run flutter pub get.


2. Configure pubspec.yaml:
1 f l utt er_n at iv e_ s p l a s h :
2 color : "# FFFFFF "
3 image : assets / splash . png
4 android : true
5 ios : true
6 fill : true

• color: Background color.


• image: Splash image (e.g., 512x512 PNG).
• fill: Scales image to fill the screen.
3. Prepare Image:
• Place splash.png in assets/ and declare in pubspec.yaml:
1 flutter :
2 assets :
3 - assets / splash . png

4. Generate Splash Screen:


1 flutter pub run f l u t t e r _ n a t i v e _ s p l a s h : create

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 7

• Android: Updates android/app/src/main/res/drawable/launch_background.xml


and creates image resources.
• iOS: Updates ios/Runner/Assets.xcassets/LaunchImage.imageset and LaunchScreen.s
5. Verify:
• Android: Check android/app/src/main/res/values/styles.xml for Theme.AppCompat.Li
and splash resources.
• iOS: Open LaunchScreen.storyboard in Xcode to confirm the image and
background.
Example: A music app uses a branded splash screen with a logo and blue background,
ensuring a polished launch experience on both platforms.

1.6 How do you customize the splash screen background color and image for
an Android Flutter app?
To customize the splash screen for Android:
1. Use flutter_native_splash:
• Configure in pubspec.yaml:
1 fl ut t er_n at i v e _ s p l a s h :
2 color : "#42 A5F5 "
3 image : assets / splash . png
4 android : true

• Run flutter pub run fluttern atives plash : create.


2. Manual Customization:
• Open android/app/src/main/res/drawable/launch_background.xml:
1 <? xml version = " 1.0 " encoding = " utf -8 " ? >
2 < layer - list xmlns:android = " http: // schemas . android . com / apk
/ res / android " >
3 < item android:drawable = " @color / splash _backg round " / >
4 < item >
5 < bitmap
6 android:gravity = " center "
7 android:src = " @drawable / splash " / >
8 </ item >
9 </ layer - list >

• Define the background color in android/app/src/main/res/values/colors.xml:


1 < resources >
2 < color name = " splash_ backg round " > #42 A5F5 </ color >
3 </ resources >

• Place the splash image (splash.png) in android/app/src/main/res/drawable/.


3. Adaptive Scaling:

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 8

• Add images for different DPIs in drawable-mdpi, drawable-hdpi, etc., to


ensure clarity on various screens.
4. Verify Style:
• In android/app/src/main/res/values/styles.xml, ensure the splash theme
is applied:
1 < style name = " LaunchTheme " parent = " Theme . AppCompat . Light .
NoActionBar " >
2 < item name = " a n d r o i d : w i n d o w B a c k g r o u n d " > @drawable /
launch _backg round </ item >
3 </ style >

Example: A gaming app sets a vibrant red splash background (#FF0000) with a centered
logo, ensuring high-resolution display on Android devices.

1.7 What is the difference between debug and release build modes in Flut-
ter?
Flutter supports multiple build modes, with debug and release being the most common:
• Debug Mode:
– Purpose: Development and testing.
– Characteristics:
∗ Includes debugging symbols and tools (e.g., hot reload).
∗ Larger app size due to unoptimized code.
∗ Slower performance (uses JIT compilation).
∗ Assert statements are enabled.
– Command: flutter run or flutter run –debug.
– Use Case: Testing UI changes in a to-do app with hot reload.
• Release Mode:
– Purpose: Production deployment.
– Characteristics:
∗ Optimized with AOT compilation for speed.
∗ Minified code and resources (smaller size, e.g., 20% reduction).
∗ No debugging symbols; assert statements are disabled.
∗ Faster performance (e.g., smoother animations).
– Command: flutter run –release or flutter build apk –release.
– Use Case: Deploying a shopping app to Google Play with optimal perfor-
mance.
• Key Differences:

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 9

– Performance: Release is faster due to AOT and optimizations.


– Size: Release APKs are smaller (e.g., 10 MB vs. 15 MB).
– Debugging: Debug supports hot reload; release does not.
– Usage: Debug for development; release for end users.
Example: A developer uses debug mode to tweak a Flutter games UI, then builds in
release mode for a 30% smaller APK with 60fps gameplay.

1.8 What command is used to generate a signed APK for Android deploy-
ment?
To generate a signed APK for Android:
1. Ensure Signing Configuration: Set up signingConfigs in android/app/build.gradle
(see Question 1).
2. Build Command:
1 flutter build apk -- release

• Outputs the signed APK to build/app/outputs/flutter-apk/app-release.apk.


3. Alternative (App Bundle):
1 flutter build appbundle -- release

• Generates build/app/outputs/bundle/release/app-release.aab, preferred


for Google Play.
4. Verify: Check the APK with jarsigner -verify -verbose build/app/outputs/flutter-apk
Example: A social media app uses flutter build appbundle –release to create a
signed AAB for Google Play, ensuring compatibility with modern devices.

1.9 How can you generate and use a keystore for signing an Android Flutter
app?
A keystore is required to sign Android APKs/AABs for authenticity.
1. Generate Keystore:
• Run:
1 keytool - genkey -v - keystore mykeystore . jks - keyalg RSA -
keysize 2048 - validity 10000 - alias mykey

• Enter details (password, name, organization) and store mykeystore.jks se-


curely (e.g., android/app/).
2. Configure build.gradle:
1 signingConfigs {
2 release {
3 keyAlias ’ mykey ’

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 10

4 keyPassword ’ password ’
5 storeFile file ( ’ mykeystore . jks ’)
6 storePassword ’ password ’
7 }
8 }
9 buildTypes {
10 release {
11 signingConfig signingConfigs . release
12 }
13 }

3. Store Passwords Securely:


• Create key.properties in android/:
1 storePassword = password
2 keyPassword = password
3 keyAlias = mykey
4 storeFile =../ app / mykeystore . jks

• Load in build.gradle:
1 def k ey sto re P r o p e r t i e s F i l e = rootProject . file (" key .
properties ")
2 def keystor eP ro pe rt ies = new Properties ()
3 keystorePro pe rt ie s . load ( new FileInputStream (
key s t or eP r o p e r t i e s F i l e ) )
4

5 signingConfigs {
6 release {
7 keyAlias ke ys to re Pro pe rt ie s [ ’ keyAlias ’]
8 keyPassword ke ys to re Pr op ert ie s [ ’ keyPassword ’]
9 storeFile file ( key st or eP ro pe rt ie s [ ’ storeFile ’])
10 storePassword ke ys tor eP ro pe rt ie s [ ’ storePassword ’]
11 }
12 }

4. Build Signed APK/AAB:


1 flutter build apk -- release

Example: A delivery app generates a keystore, configures it, and builds a signed AAB
for secure Play Store deployment.

1.10 Which tools are required to publish a Flutter app on the Google Play
Store?
• Flutter SDK: For building the app (flutter build appbundle).
• Android Studio: Configures Android SDK, Gradle, and emulators for testing.
• Keytool: Generates keystores for signing (part of JDK).

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 11

• Google Play Console: Manages app listings, uploads AABs, and tracks metrics
($25 one-time fee).
• Bundletool: Tests AABs locally (bundletool build-apks).
• Git: Manages version control for collaborative development.
• Image Editing Tools: Creates Play Store assets (e.g., Photoshop for icons, screen-
shots).
Example: A developer uses Android Studio to build a Flutter app, keytool for signing,
and Google Play Console to publish a fitness tracker app.

1.11 What are the prerequisites for deploying a Flutter app to the Apple
App Store?
• Apple Developer Account: $99/year for App Store access.
• MacOS Device: Required for Xcode and iOS builds.
• Xcode: Version 15+ for building, signing, and uploading apps.
• Flutter SDK: Configured for iOS builds (flutter doctor).
• Provisioning Profiles and Certificates: For code signing (see Question 12).
• App Store Connect: Manages app metadata, screenshots, and submissions.
• iOS Device/Simulator: For testing on various screen sizes (e.g., iPhone 14, iPad).
• App-Specific Details:
– Unique bundle ID (e.g., com.example.myapp).
– App icon set (via flutter_launcher_icons).
– Privacy policy and compliance with App Store guidelines.
Example: A meditation app requires an Apple Developer account, Xcode, and a provi-
sioning profile to submit to the App Store.

1.12 How do you set up provisioning profiles and signing certificates for iOS
deployment?
1. Apple Developer Account:
• Enroll at https://developer.apple.com ($99/year).
2. Create App ID:
• In the Apple Developer Portal, go to Identifiers > App IDs.
• Register a unique bundle ID (e.g., com.example.myapp).
3. Generate Certificates:
• In the Portal, go to Certificates > Create Certificate.
• Create an iOS Distribution certificate.

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 12

• Generate a Certificate Signing Request (CSR) via Keychain Access on macOS,


upload it, and download the .cer file.
4. Create Provisioning Profile:
• Go to Profiles > Create Profile.
• Select App Store distribution, link to the App ID, and select the certificate.
• Download the .mobileprovision file.
5. Configure Xcode:
• Open ios/Runner.xcworkspace in Xcode.
• Go to Target > Runner > Signing & Capabilities.
• Enable Automatically manage signing or manually import the certificate
and profile.
• Set the team to your Apple Developer account.
6. Verify in Flutter:
• Update ios/Runner/Info.plist with the correct bundle ID.
• Run flutter build ios –release to ensure signing works.
Example: A journal app sets up a provisioning profile for com.myapp.journal, signs with
an iOS Distribution certificate, and builds via Xcode.

1.13 Explain the role of Xcode in building and publishing iOS Flutter ap-
plications.
Xcode is Apples IDE, critical for iOS Flutter apps:
• Building: Compiles Flutters Dart code and native iOS components (Swift/Objective-
C) into an IPA file using flutter build ios.
• Device Testing: Manages iOS simulators and physical devices for debugging.
• Signing: Configures provisioning profiles and certificates for code signing (manu-
ally or automatically).
• Asset Management: Handles icons, launch screens, and other resources in Assets.xcassets.
• Publishing: Uses Archive to create an IPA and uploads it to App Store Connect
via Application Loader or Transporter.
• Configuration: Edits Info.plist and project settings (e.g., entitlements, capa-
bilities like push notifications).
Example: For a Flutter chat app, Xcode configures push notifications, signs the build,
and uploads the IPA to App Store Connect.

1.14 What command is used to compile and generate web assets in a Flutter
web app?
To compile a Flutter app for web:

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 13

1 flutter build web

• Output: Generates assets in build/web/, including index.html, main.dart.js,


and static files.
• Options:
– –release: Optimized build for production.
– –profile: For performance profiling.
– –web-renderer canvaskit: Uses CanvasKit for better graphics (larger size).
– –web-renderer html: Uses HTML renderer for smaller size.
• Prerequisites: Enable web support with flutter config –enable-web.
Example: A portfolio app runs flutter build web –release to create a production-
ready web app.

1.15 How do you host a Flutter web app using GitHub Pages or Firebase
Hosting?
• GitHub Pages:
1. Build the web app: flutter build web.
2. Create a GitHub repository (e.g., myapp).
3. Push the build/web contents to a gh-pages branch:
1 git add build / web
2 git commit -m " Deploy web app "
3 git subtree push -- prefix build / web origin gh - pages

4. In the repository settings, enable GitHub Pages for the gh-pages branch.
5. Access the app at https://username.github.io/myapp.
• Firebase Hosting:
1. Install Firebase CLI: npm install -g firebase-tools.
2. Login: firebase login.
3. Initialize hosting: firebase init hosting in the Flutter project root.
4. Set public directory to build/web in firebase.json.
5. Build the app: flutter build web.
6. Deploy: firebase deploy.
7. Access at the provided Firebase URL (e.g., https://myapp.web.app).
Example: A blog app uses Firebase Hosting for fast, scalable deployment with automatic
SSL, while GitHub Pages suits a simple portfolio.

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 14

1.16 What files are generated in the build/web folder after building a Flutter
web app?
Running flutter build web generates:
• index.html: Entry point for the web app, loading Flutter scripts.
• main.dart.js: Compiled Dart code as JavaScript.
• flutter_service_worker.js: Service worker for offline support (PWA).
• assets/: Fonts, images, and other resources from pubspec.yaml.
• canvaskit/ (if CanvasKit renderer): WebAssembly for advanced graphics.
• manifest.json: PWA configuration for icons and metadata.
• version.json: Build metadata.
Example: A dashboard apps build/web includes index.html for rendering and assets/images/logo.pn
for branding.

1.17 What are the benefits and limitations of deploying a Flutter app to the
web?
• Benefits:
– Single Codebase: Reuse mobile app code for web, reducing development
time (e.g., 90% code reuse in a news app).
– Broad Reach: Accessible on browsers without installation (e.g., Chrome,
Safari).
– PWA Support: Offline capabilities and installable apps (e.g., a task app as
a PWA).
– Fast Deployment: Hosting on Firebase or GitHub Pages is quick and scal-
able.
• Limitations:
– Performance: Web apps are slower than native due to JavaScript (e.g., 30%
slower animations).
– Limited Native Access: No direct hardware access (e.g., camera, GPS).
– Size: CanvasKit renderer increases size (e.g., 10 MB vs. 2 MB with HTML
renderer).
– Browser Compatibility: Some features may vary across browsers (e.g., Sa-
fari quirks).
Example: A Flutter e-commerce web app offers broad access but may need optimization
for smooth scrolling compared to its native version.

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 15

2 Programming Questions
2.1 Create a simple UI design to demonstrate the use of ElevatedButton
and Container Widgets.
This code creates a screen with a styled Container and an ElevatedButton that prints
a message when clicked.
1 import ’ package : flutter / material . dart ’;
2

3 void main () = > runApp ( MyApp () ) ;


4

5 class MyApp extends StatelessWidget {


6 @override
7 Widget build ( BuildContext context ) {
8 return MaterialApp (
9 home : Scaffold (
10 appBar : AppBar ( title : Text ( ’ Button and Container Demo ’) ) ,
11 body : Center (
12 child : Container (
13 width : 300 ,
14 padding : EdgeInsets . all (16) ,
15 decoration : BoxDecoration (
16 color : Colors . blue [100] ,
17 borderRadius : BorderRadius . circular (12) ,
18 boxShadow : [ BoxShadow ( color : Colors . grey ,
blurRadius : 8) ] ,
19 ),
20 child : Column (
21 mainAxisSize : MainAxisSize . min ,
22 children : [
23 Text (
24 ’ Welcome ! ’ ,
25 style : TextStyle ( fontSize : 24 , fontWeight :
FontWeight . bold ) ,
26 ),
27 SizedBox ( height : 16) ,
28 ElevatedButton (
29 onPressed : () = > print ( ’ Button Pressed ! ’) ,
30 style : ElevatedButton . styleFrom (
31 backgroundColor : Colors . blue ,
32 foregroundColor : Colors . white ,
33 padding : EdgeInsets . symmetric ( horizontal : 24 ,
vertical : 12) ,
34 ),
35 child : Text ( ’ Click Me ’) ,
36 ),
37 ],
38 ),
39 ),
40 ),
41 ),

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 16

42 );
43 }
44 }

Explanation: - Container: Styles a card-like box with padding, a light blue back-
ground, rounded corners, and a shadow. - ElevatedButton: Triggers a console print
when pressed, styled with a blue background and white text. - Use Case: A login screen
with a styled button in a card.

2.2 Create a simple UI design to demonstrate the use of Text and Image
Widgets.
This code displays a centered Text and Image widget.
1 import ’ package : flutter / material . dart ’;
2

3 void main () = > runApp ( MyApp () ) ;


4

5 class MyApp extends StatelessWidget {


6 @override
7 Widget build ( BuildContext context ) {
8 return MaterialApp (
9 home : Scaffold (
10 appBar : AppBar ( title : Text ( ’ Text and Image Demo ’) ) ,
11 body : Center (
12 child : Column (
13 mainAxisAlig nment : MainA xisAli gnment . center ,
14 children : [
15 Text (
16 ’ Explore Nature ’ ,
17 style : TextStyle (
18 fontSize : 28 ,
19 fontWeight : FontWeight . bold ,
20 color : Colors . green [800] ,
21 ),
22 ),
23 SizedBox ( height : 20) ,
24 Image . asset (
25 ’ assets / nature . jpg ’ ,
26 width : 300 ,
27 height : 200 ,
28 fit : BoxFit . cover ,
29 ),
30 ],
31 ),
32 ),
33 ),
34 );
35 }
36 }

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 17

Explanation: - Text: Displays a bold, green title with a large font. - Image.asset:
Loads a local image (add assets/nature.jpg to pubspec.yaml). - Setup: Add to
pubspec.yaml:
1 flutter :
2 assets :
3 - assets / nature . jpg

- Use Case: A travel apps homepage with a title and hero image.

2.3 Write a Flutter code to implement state management. (Change the


states)
This code uses a StatefulWidget to manage a counters state.
1 import ’ package : flutter / material . dart ’;
2

3 void main () = > runApp ( MyApp () ) ;


4

5 class MyApp extends StatelessWidget {


6 @override
7 Widget build ( BuildContext context ) {
8 return MaterialApp (
9 home : CounterScreen () ,
10 );
11 }
12 }
13

14 class CounterScreen extends StatefulWidget {


15 @override
16 _Co u nter Sc re en St at e createState () = > _C o u n te r S cr e e nS t a te () ;
17 }
18

19 class _Coun te rS cr ee nS t a te extends State < CounterScreen > {


20 int _counter = 0;
21

22 void _incrementCounter () {
23 setState (() {
24 _counter ++;
25 }) ;
26 }
27

28 @override
29 Widget build ( BuildContext context ) {
30 return Scaffold (
31 appBar : AppBar ( title : Text ( ’ Counter App ’) ) ,
32 body : Center (
33 child : Column (
34 mainAxisAlig nment : MainAx isAli gnment . center ,
35 children : [
36 Text ( ’ Count : $_counter ’ , style : TextStyle ( fontSize :
24) ) ,

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 18

37 SizedBox ( height : 16) ,


38 ElevatedButton (
39 onPressed : _incrementCounter ,
40 child : Text ( ’ Increment ’) ,
41 ),
42 ],
43 ),
44 ),
45 );
46 }
47 }

Explanation: - StatefulWidget: Manages mutable state (_counter). - setState:


Updates the UI when the counter increments. - ElevatedButton: Triggers state change
via _incrementCounter. - Use Case: A voting app tracking user clicks.

2.4 Create an app with five screens and switch between them using buttons
This code creates an app with five screens, navigable via buttons.
1 import ’ package : flutter / material . dart ’;
2

3 void main () = > runApp ( MyApp () ) ;


4

5 class MyApp extends StatelessWidget {


6 @override
7 Widget build ( BuildContext context ) {
8 return MaterialApp (
9 initialRoute : ’/ ’ ,
10 routes : {
11 ’/ ’: ( context ) = > Screen1 () ,
12 ’/ screen2 ’: ( context ) = > Screen2 () ,
13 ’/ screen3 ’: ( context ) = > Screen3 () ,
14 ’/ screen4 ’: ( context ) = > Screen4 () ,
15 ’/ screen5 ’: ( context ) = > Screen5 () ,
16 },
17 );
18 }
19 }
20

21 class Screen1 extends StatelessWidget {


22 @override
23 Widget build ( BuildContext context ) {
24 return Scaffold (
25 appBar : AppBar ( title : Text ( ’ Screen 1 ’) ) ,
26 body : Center (
27 child : ElevatedButton (
28 onPressed : () = > Navigator . pushNamed ( context , ’/ screen2
’) ,
29 child : Text ( ’ Go to Screen 2 ’) ,
30 ),
31 ),

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 19

32 );
33 }
34 }
35

36 class Screen2 extends StatelessWidget {


37 @override
38 Widget build ( BuildContext context ) {
39 return Scaffold (
40 appBar : AppBar ( title : Text ( ’ Screen 2 ’) ) ,
41 body : Center (
42 child : Column (
43 mainAxisAlig nment : MainAx isAli gnment . center ,
44 children : [
45 ElevatedButton (
46 onPressed : () = > Navigator . pushNamed ( context , ’/
screen3 ’) ,
47 child : Text ( ’ Go to Screen 3 ’) ,
48 ),
49 ElevatedButton (
50 onPressed : () = > Navigator . pop ( context ) ,
51 child : Text ( ’ Back ’) ,
52 ),
53 ],
54 ),
55 ),
56 );
57 }
58 }
59

60 class Screen3 extends StatelessWidget {


61 @override
62 Widget build ( BuildContext context ) {
63 return Scaffold (
64 appBar : AppBar ( title : Text ( ’ Screen 3 ’) ) ,
65 body : Center (
66 child : Column (
67 mainAxisAlig nment : MainAx isAli gnment . center ,
68 children : [
69 ElevatedButton (
70 onPressed : () = > Navigator . pushNamed ( context , ’/
screen4 ’) ,
71 child : Text ( ’ Go to Screen 4 ’) ,
72 ),
73 ElevatedButton (
74 onPressed : () = > Navigator . pop ( context ) ,
75 child : Text ( ’ Back ’) ,
76 ),
77 ],
78 ),
79 ),
80 );

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 20

81 }
82 }
83

84 class Screen4 extends StatelessWidget {


85 @override
86 Widget build ( BuildContext context ) {
87 return Scaffold (
88 appBar : AppBar ( title : Text ( ’ Screen 4 ’) ) ,
89 body : Center (
90 child : Column (
91 mainAxisAlig nment : MainAx isAli gnment . center ,
92 children : [
93 ElevatedButton (
94 onPressed : () = > Navigator . pushNamed ( context , ’/
screen5 ’) ,
95 child : Text ( ’ Go to Screen 5 ’) ,
96 ),
97 ElevatedButton (
98 onPressed : () = > Navigator . pop ( context ) ,
99 child : Text ( ’ Back ’) ,
100 ),
101 ],
102 ),
103 ),
104 );
105 }
106 }
107

108 class Screen5 extends StatelessWidget {


109 @override
110 Widget build ( BuildContext context ) {
111 return Scaffold (
112 appBar : AppBar ( title : Text ( ’ Screen 5 ’) ) ,
113 body : Center (
114 child : ElevatedButton (
115 onPressed : () = > Navigator . pop ( context ) ,
116 child : Text ( ’ Back ’) ,
117 ),
118 ),
119 );
120 }
121 }

Explanation: - MaterialApp.routes: Defines named routes for navigation. - Navigator.pushNamed:


Navigates to the next screen. - Navigator.pop: Returns to the previous screen. - Use
Case: A tutorial app with sequential screens for onboarding.

2.5 Create a simple code to demonstrate asynchronous data loading using


FutureBuilder.
This code fetches a string after a delay using FutureBuilder.

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 21

1 import ’ package : flutter / material . dart ’;


2

3 void main () = > runApp ( MyApp () ) ;


4

5 class MyApp extends StatelessWidget {


6 @override
7 Widget build ( BuildContext context ) {
8 return MaterialApp (
9 home : Scaffold (
10 appBar : AppBar ( title : Text ( ’ FutureBuilder Demo ’) ) ,
11 body : Center (
12 child : FutureBuilder < String >(
13 future : fetchData () ,
14 builder : ( context , snapshot ) {
15 if ( snapshot . connectionState == ConnectionState .
waiting ) {
16 return C i r c u l a r P r o g r e s s I n d i c a t o r () ;
17 } else if ( snapshot . hasError ) {
18 return Text ( ’ Error : $ { snapshot . error } ’) ;
19 } else if ( snapshot . hasData ) {
20 return Text ( snapshot . data ! , style : TextStyle (
fontSize : 24) ) ;
21 }
22 return Text ( ’ No Data ’) ;
23 },
24 ),
25 ),
26 ),
27 );
28 }
29

30 Future < String > fetchData () async {


31 await Future . delayed ( Duration ( seconds : 2) ) ;
32 return ’ Data Loaded ! ’;
33 }
34 }

Explanation: - FutureBuilder: Builds UI based on a Futures state (waiting, error,


data). - fetchData: Simulates async data loading with a 2-second delay. - Use Case: A
weather app displaying a forecast after fetching API data.

2.6 Write a short note on how an e-commerce app fetches product data from
an API.
An e-commerce app fetches product data from a REST API to display items like clothing
or electronics. The process involves:
• API Request: The app uses the http package to send a GET request to an
endpoint (e.g., https://api.shop.com/products).
• JSON Parsing: The API returns JSON data (e.g., {"id": 1, "name": "Shirt",

Generated by Grok 3, xAI


Flutter Unit 6 Question Bank Solutions 22

"price": 29.99}), which is parsed into Dart models using jsonDecode and a
Product class with fromJson.
• State Management: The fetched data is stored in a state management solution
(e.g., Provider) to update the UI.
• UI Display: A FutureBuilder or ListView.builder renders the products in a
grid or list, showing names, prices, and images.
• Error Handling: The app handles errors (e.g., network failures) with try-catch
and displays a retry button.
Example: Amazons Flutter app fetches product JSON, maps it to Product objects, and
displays items in a GridView, with caching via dio for offline access.

Generated by Grok 3, xAI

You might also like