0% found this document useful (0 votes)
16 views75 pages

Flutter Installation and Layout Guide

The document provides a comprehensive guide to setting up Flutter and Dart SDK, exploring Flutter widgets, and creating responsive UIs. It includes step-by-step instructions for installing Flutter, writing Dart programs, and implementing various layout structures using Row, Column, and Stack widgets. Additionally, it covers navigation between screens using the Navigator class and named routes for better management in Flutter applications.

Uploaded by

hitsaiml2c
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)
16 views75 pages

Flutter Installation and Layout Guide

The document provides a comprehensive guide to setting up Flutter and Dart SDK, exploring Flutter widgets, and creating responsive UIs. It includes step-by-step instructions for installing Flutter, writing Dart programs, and implementing various layout structures using Row, Column, and Stack widgets. Additionally, it covers navigation between screens using the Navigator class and named routes for better management in Flutter applications.

Uploaded by

hitsaiml2c
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

UI Flutter

Lab Session 1
a) Install flutter and Dart sdk
To install Flutter and the Dart SDK, you can follow these steps:
a) Download Flutter: Visit the Flutter website's Get Started page and download the
Flutter SDK for your operating system (Windows, macOS, or Linux).
b) Extract the Flutter SDK: After downloading, extract the contents of the compressed
file to a location on your computer where you want to store the Flutter SDK. For
example, you can extract it to C:\flutter on Windows, /Users//flutter on macOS, or
~/flutter on Linux.
c) Add Flutter to your PATH: Update your system's PATH variable to include the
Flutter bin directory. This step allows you to execute Flutter commands from any
directory in your terminal or command prompt. The precise steps for updating the
PATH vary depending on your operating system. Windows: From the Start search bar,
type 'env' and select 'Edit the system environment variables'. Click on 'Environment
Variables'. Under 'System Variables', find the 'Path' variable, select it, and click 'Edit'.
Click 'New' and add the path to the bin directory inside the Flutter directory (e.g.,
C:\flutter\bin). Click 'OK' on all open dialogs to save your changes. macOS and Linux:
Open a terminal window. Run the following command to open the profile file associated
with your terminal (.bash_profile, .bashrc, .zshrc, or similar): nano ~/.bash_profile Add
the following line at the end of the file: export PATH="$PATH:/path/to/flutter/bin"
Press Ctrl + X to exit, then Y to save changes, and Enter to confirm.
d) Verify the Flutter installation: Open a new terminal window, and run the following
command to verify that Flutter is properly installed: flutter --version This command
should display the Flutter version and other relevant information if the installation was
successful.
e) Install Flutter dependencies: Depending on your development environment, you may
need to install additional dependencies, such as Android Studio to fully set up your
Flutter development environment.
f) Download Dart SDK (if not bundled with Flutter): Flutter comes with the Dart SDK
bundled, so if you've installed Flutter, you should have the Dart SDK as well. However,
if you need to install Dart separately, you can download it from the Dart "SDK
archive".

1
UI Flutter

b) Write a simple dart program to understand the language


basics

2
UI Flutter

OUTPUT:

3
UI Flutter

Lab Session 2
a) Explore various flutter widgets

Flutter provides a rich set of widgets to build user interfaces for mobile, web, and
desktop applications. These widgets help in creating visually appealing and interactive
UIs. Here are some of the commonly used Flutter widgets categorized by their
functionalities:

Layout Widgets:

 Container: A versatile widget that can contain other widgets and provides
options for alignment, padding, margin, and decoration.
 Row and Column: Widgets that arrange their children in a horizontal or vertical
line respectively.
 Stack: Allows widgets to be stacked on top of each other, enabling complex
layouts.
 ListView and GridView: Widgets for displaying a scrollable list or grid of
children, with support for various layouts and scrolling directions.
 Scaffold: Implements the basic material design layout structure, providing app
bars, drawers, and floating action buttons.

Text and Styling Widgets:

 Text: Displays a string of text with options for styling such as font size, color, and
alignment.
 RichText: Allows for more complex text styling and formatting, including
different styles within the same text span.
 TextStyle: A class for defining text styles that can be applied to Text widgets.

Input Widgets:

 TextField: A widget for accepting user input as text, with options for
customization and validation.
 Checkbox and Radio: Widgets for selecting from a list of options, either through
checkboxes or radio buttons.
 DropdownButton: Provides a dropdown menu for selecting from a list of
options.

4
UI Flutter

Button Widgets:

 ElevatedButton and TextButton: Widgets for displaying buttons with different


styles and customization options.
 IconButton: A button widget that displays an icon and responds to user taps.
 GestureDetector: A versatile widget that detects gestures such as taps, swipes,
and drags, allowing for custom interactions.

Image and Icon Widgets:

 Image: Widget for displaying images from various sources, including assets,
network URLs, and memory.
 Icon: Displays a Material Design icon.

Navigation Widgets:

 Navigator: Manages a stack of route objects and transitions between different


screens or pages in the app.
 PageRouteBuilder: A customizable widget for building page transitions and
animations.

Animation Widgets:

 AnimatedContainer: An animated version of the Container widget, with support


for transitioning properties over a specified duration.
 AnimatedOpacity, AnimatedPositioned, AnimatedBuilder: Widgets for
animating opacity, position, and custom properties respectively.

Material Design Widgets:

 AppBar: A material design app bar that typically contains a title, leading and
trailing widgets, and actions.
 BottomNavigationBar: Provides a navigation bar at the bottom of the screen for
switching between different screens or tabs.
 Card: Displays content organized in a card-like structure with optional elevation
and padding.

Cupertino (iOS-style) Widgets:

 CupertinoNavigationBar: A navigation bar in the iOS style.


 CupertinoButton: A button widget with the iOS style.
 CupertinoTextField: A text field widget with the iOS style.

5
UI Flutter

b) User implement different layout structures using Row,


Column, and Stack widgets

Objective:
To create and execute a Flutter project named Flutter_Layouts that demonstrates
different layout structures using Row, Column, and Stack widgets.

Instructions:
Step 1: Creating a Folder in Documents

1. Open File Explorer.


2. Go to the Documents folder.
3. Right-click → Select New → Folder.
4. Name the folder with your Name or Roll Number.
5. This folder will store your Flutter project.

Step 2: Creating a New Flutter Project Named Flutter_Layouts

1. Open Visual Studio Code


o Click on the Start Menu → Search for Visual Studio Code → Open it.
2. Open Command Palette
o Click View → Command Palette...
o Or press Ctrl + Shift + P.
3. Select “Flutter: New Project”
o In the search bar, type Flutter.
o From the list, choose “Flutter: New Project”.
4. Choose Project Type
o When prompted, select Application.
5. Enter Project Name
o Type the name exactly as:
o Flutter_Layouts
o Press Enter.
6. Select Project Location
o When asked where to create the project, navigate to your Documents
folder → open the folder you created (with your name or roll number).
o Click Select Folder (or OK).
7. Wait for Project Setup
o VS Code will automatically create all files.
o Wait until you see:
“All done! Your Flutter app is ready.”
8. Verify Project Structure

6
UI Flutter

Step 3: Creating New Dart Files in the lib Folder

In Flutter, all Dart files are stored in the lib folder.


You will now create separate Dart files for Row, Column, and Stack layouts.

Steps to Create New Files

1. In VS Code, open your project Flutter_Layouts.


2. On the left side Explorer panel, click on the lib folder to expand it.
3. Right-click on the lib folder → select New File.
4. Create the following three files one by one:
o week_2_b_row.dart
o week_2_b_column.dart
o week_2_b_stack.dart
5. Each file will contain its respective layout code (Row, Column, or Stack).
6. Save each file after adding the code (Ctrl + S).

7
UI Flutter

Step 4: Replace Code in [Link]

Note:
The [Link] file is the starting point of every Flutter app.
It contains the main() function that launches the app using runApp().

Steps:

1. Open your project in VS Code.


2. Go to:
3. lib → [Link]
4. Delete all existing code inside the file.
5. Copy and paste the below Layout Selector code into [Link].
6. Make sure the three layout files you created earlier are saved inside lib.
7. Save the file (Ctrl + S).

8
UI Flutter

Code to type in [Link]

Step 5: Running the Flutter Project

9
UI Flutter

How to Open a New Terminal and Run the Program

1. Make sure your project Flutter_Layouts is open in VS Code.


2. Click View → Terminal or press Ctrl + ` (key below Esc).
3. A terminal will appear at the bottom of the screen.
4. Check available devices:
5. flutter devices

You’ll see options like:

o
Chrome (web)
o
Windows (desktop)
o
Emulator (mobile)
6. Run the app:
7. flutter run
8. When asked to select a device, type the number for Chrome (for example, 2) and
press Enter.
9. The Flutter app will open in your web browser or emulator.
10. To stop it, press Ctrl + C in the terminal.

Result:

 Clicking Show Row Layout displays three boxes arranged horizontally.


 Clicking Show Column Layout displays boxes vertically.
 Clicking Show Stack Layout displays boxes overlapping each other (one on top
of another).

Description of Files

File / Folder Name Description

[Link] Entry point of the Flutter app. Contains the layout selector menu.

week_2_b_row.dart Contains Flutter code for Row Layout (horizontal).

week_2_b_column.dart Contains Flutter code for Column Layout (vertical).

week_2_b_stack.dart Contains Flutter code for Stack Layout (overlapping).

[Link] Configuration file for Flutter dependencies.

lib/ Main folder containing all Dart source files.

build/ Auto-generated folder with compiled files.

1. Row Layout:

10
UI Flutter

11
UI Flutter

OUTPUT:

12
UI Flutter

2) Column Layout:

13
UI Flutter

OUTPUT:

14
UI Flutter

3) Stack Layout:

15
UI Flutter

OUTPUT:

16
UI Flutter

Lab Session 3
(a): Design a Responsive UI That Adapts to Different Screen Sizes

Objective:
To design and develop a Responsive User Interface (UI) in Flutter that automatically
adjusts its layout for different screen sizes using the LayoutBuilder widget.

Theory:
Responsive design allows applications to look good on all devices—mobiles, tablets, and
desktops—by changing the layout depending on the screen width.
In Flutter, this can be achieved using the LayoutBuilder widget, which provides the current
BoxConstraints (like maxWidth).

If the available width is small (e.g., < 600 px), a Narrow Layout is displayed.
If the width is larger, a Wide Layout is shown.

Procedure:
Step 1: Create a New Flutter Project

(Use the same folder created in Lab Session 2.)

1. Open Visual Studio Code.


o Click on View → Command Palette...
o Or press Ctrl + Shift + P.
2. Select “Flutter: New Project”.
o Type Flutter in the search box.
o Choose Flutter: New Project → Application.
3. Enter the Project Name.
o Type:
o responsive_ui
4. Select Location.
o Navigate to the folder you created earlier (for example):
o Click Select Folder (or OK).
5. Wait for Setup.
o VS Code will create the project and display:
“All done! Your Flutter app is ready.”

Step 2: Write the Program

1. In the left Explorer panel, open:


2. lib → [Link]
3. Delete all existing code.
4. Copy and paste the following program

17
UI Flutter

Program:

18
UI Flutter

Step 3: Running the Program

1. In VS Code, open the terminal (View → Terminal or Ctrl + `).


2. Type:
3. flutter run
4. Select Chrome (option 2) as the device.
5. The app will open in your browser.
6. Resize the Chrome window and observe how the layout changes for different widths:
o Mobile Layout (width < 600 px)
o Tablet Layout (600 px ≤ width < 1200 px)
o Desktop Layout (width ≥ 1200 px)

Output:
Screen Type Layout Displayed

Mobile (Width < 600 px) Flutter logo, text, and button arranged vertically

Tablet (Width < 1200 px) Flutter logo and content arranged side-by-side

Desktop (Width ≥ 1200 px) Flutter logo, text, and button displayed in a spacious horizontal layout

Result:
The Flutter application successfully uses Media Queries and Breakpoints to implement
responsive layouts for Mobile, Tablet, and Desktop screens.

19
UI Flutter

20
UI Flutter

21
UI Flutter

Lab Session 4
(a): Setup Navigation Between Different Screens Using Navigator

Objective:
To implement screen navigation in Flutter using the Navigator class to move between
multiple screens in an application.

Theory:
Navigation is one of the most important parts of app development.
Flutter provides the Navigator class to manage routes (pages) in the application stack.

 [Link]() → Used to move from one screen to another.


 [Link]() → Used to go back to the previous screen.

Concept:

 Each screen in Flutter is represented by a Widget (commonly a Scaffold widget).


 Screens are managed as a stack — new screens are pushed onto the stack, and popped
when returning.

Procedure:
Step 1: Create a New Flutter Project

1. Open VS Code.
2. Click View → Command Palette... or press Ctrl + Shift + P.
3. Select Flutter: New Project → Application.
4. Enter the project name:
5. navigation_example
6. Select the same folder created in Lab Session 2 .
7. Wait for the message:
“All done! Your Flutter app is ready.”

Step 2: Write the Program

1. In VS Code, open:
2. lib → [Link]
3. Delete all existing code.
4. Copy and paste the following code exactly as shown below.

22
UI Flutter

Program:

Step 3: Run the Program

1. Open the terminal (View → Terminal or press Ctrl + `).


2. In the terminal, type:
3. flutter run
4. Select Chrome (option 2) or Windows (option 1).
5. The app will launch showing the First Screen.

23
UI Flutter

Step 4: Observe the Output


Output Description:

1. The first screen displays a button labeled “Go to Second Screen”.


2. When you click it, the app navigates to the Second Screen using [Link]().
3. The second screen displays a button labeled “Go back to First Screen”.
4. When clicked, it returns to the First Screen using [Link]().

Output:

Screen Action Result

First Screen Click “Go to Second Screen” Navigates to Second Screen

Click “Go back to First


Second Screen Returns to First Screen
Screen”

Result:

The Flutter application successfully demonstrates navigation between two screens using
[Link]() and [Link]() methods.

24
UI Flutter

(b): Implement Navigation with Named Routes

Objective:
To implement navigation between multiple screens in a Flutter application using named
routes.

Theory:
In Flutter, navigation helps users move between different screens (called routes).

There are two main types of navigation:

1. Anonymous Routes – Using [Link]() and [Link]().


2. Named Routes – Using route names like '/', '/second', etc.

Using named routes makes navigation more readable and easier to manage in large
applications.

Important Navigator Methods:

 [Link](context, '/routeName') → Navigate to a new screen.


 [Link](context) → Return to the previous screen.
 [Link](context, [Link]('/')) → Go back to a specific screen.

Procedure:
Step 1: Create a New Flutter Project

1. Open Visual Studio Code.


2. Click View → Command Palette... or press Ctrl + Shift + P.
3. Select Flutter: New Project → Application.
4. Enter the project name:
5. navigation_namedroutes
6. Select the same folder used in Lab Session 2 .
7. Wait for the setup to complete until the message appears:
“All done! Your Flutter app is ready.”

Step 2: Write the Program

1. In VS Code, open:
2. lib → [Link]
3. Delete all existing code.
4. Copy and paste the following code exactly as shown below.

25
UI Flutter

Program:

26
UI Flutter

Step 3: Run the Program

1. Open View → Terminal or press Ctrl + `.


2. In the terminal, type:
3. flutter run
4. Choose Chrome (option 2) or Windows (option 1).
5. Wait for the app to launch in your browser or emulator.

Step 4: Observe the Output


Output Description:

1. The app opens on Home Screen with a button “Go to Second Screen.”
2. Clicking it navigates to the Second Screen.
3. The Second Screen has a button “Go to Third Screen.”
4. Clicking it navigates to the Third Screen.
5. The Third Screen contains a button “Go Back to Home,”
which returns directly to the Home Screen using the named route '/'.

27
UI Flutter

Result:
The Flutter application successfully demonstrates navigation between multiple screens
using Named Routes ([Link]() and [Link]()).

28
UI Flutter

Lab Session 5
(a): Learn About Stateful and Stateless Widgets

Objective:
To understand and implement Stateless and Stateful widgets in Flutter, and to differentiate
between their behaviors in UI development.

Theory:
In Flutter, everything is a widget — even layout and design elements.
Widgets are categorized into two main types:

1. Stateless Widgets

 Definition:
Stateless widgets are widgets that do not change once they are built.
Their properties are immutable, and their UI depends only on the configuration
passed to them.
 Characteristics:
o Do not hold or modify any internal data.
o Lightweight and simple.
o Rebuilt only when their parent widget changes.
o Suitable for static UI elements such as:
 Labels
 Icons
 Buttons
 Cards
 Example Widgets:
Text, Icon, Card, RaisedButton, ListTile, etc.

2. Stateful Widgets

 Definition:
Stateful widgets are those that can change their state during the app’s lifetime.
They maintain mutable state and can rebuild their UI dynamically using setState().
 Characteristics:
o Contain both a widget and a State class.
o Used for UI elements that need to update dynamically.
o Common examples: Checkbox, TextField, Slider, Counter App, etc.

29
UI Flutter

Procedure:
Step 1: Create a New Flutter Project

1. Open Visual Studio Code.


2. Go to View → Command Palette... or press Ctrl + Shift + P.
3. Type Flutter: New Project → Application.
4. Enter the project name:
5. Stateless_Widget_Example
6. Select your lab folder .
7. Wait for setup to complete.

Step 2: Write the Program

1. Open the file:


2. lib → [Link]
3. Delete existing code.
4. Copy and paste the following program.

30
UI Flutter

Program:

31
UI Flutter

Step 3: Run the Program

1. Open View → Terminal or press Ctrl + `.


2. Type:
3. flutter run
4. Select Chrome or Windows as the target device.
5. Wait for the app to build and launch.

Step 4: Observe the Output

Output Description:

 The screen displays a scrollable list of cards.


 Each card shows:
o A title (e.g., “Card 0”, “Card 1”, etc.)
o A subtitle (“Subtitle 0”, “Subtitle 1”, etc.)
o A circular avatar showing the first letter of the card title.
 The cards are built using Stateless Widgets, so their content does not change when
tapped.

32
UI Flutter

Lab Session 5
(b): Implement State Management Using setState()

Objective:
To understand and implement state management in Flutter using the setState() method in a
Stateful widget.

Theory:
In Flutter, Stateful widgets are widgets that can change their appearance in response to
user interaction or data updates.

Stateless Widgets

 Do not change once built.


 Have no internal state.
 Example: Text, Icon, Card.

Stateful Widgets

 Maintain mutable state that can change during the app’s lifetime.
 When the state changes, the widget is rebuilt to reflect the update.
 Uses the setState() method to refresh the UI.

setState() Method

 Notifies the framework that the state has changed.


 Triggers a rebuild of the widget tree.

Syntax:

setState(() {
// update variables here
});

Example Use: A counter app where pressing a button increases the displayed number.

Procedure:
Step 1: Create a New Flutter Project

1. Open Visual Studio Code.


2. Click View → Command Palette... or press Ctrl + Shift + P.
3. Choose Flutter: New Project → Application.
4. Enter the project name:
5. counter_setstate

33
UI Flutter

6. Select your folder .


7. Wait for the project setup to complete.

Step 2: Write the Program

1. In the Explorer panel, open:


2. lib → [Link]
3. Delete any existing code.
4. Copy and paste the following program.

34
UI Flutter

Program: Counter Example Using setState()

35
UI Flutter

Step 3: Run the Program


1. Open View → Terminal or press Ctrl + `.
2. In the terminal, type:
3. flutter run
4. Select Chrome (web) or Windows (desktop) as the device.
5. Wait for the app to build and launch.

Step 4: Observe the Output


Output Description:

 The screen shows the text “Counter Value: 0”.


 Each time you tap the Floating Action Button (+), the number increases by 1.
 The UI updates automatically using the setState() method.

Action Result

Tap “+” button Counter value increases dynamically

36
UI Flutter

Lab Session 6
(a): Create Custom Widgets for Specific UI Elements

Objective:
To design and implement custom reusable widgets in Flutter for text fields and buttons,
enabling modular and maintainable UI code.

Theory:
In Flutter, widgets are the building blocks of the UI.
Creating custom widgets allows developers to:

 Reuse code efficiently.


 Maintain consistent styling across screens.
 Simplify large UI layouts.

Types of Custom Widgets:

1. Stateless Custom Widgets:


o Used for static UI components (e.g., buttons, labels).
2. Stateful Custom Widgets:
o Used for components that change dynamically (e.g., forms, inputs).

In this experiment, we create two reusable stateless custom widgets:

 CustomTextField for user input.


 CustomButton for actions.

Procedure:
Step 1: Create a New Flutter Project

1. Open VS Code → View → Command Palette...


2. Select Flutter: New Project → Application
3. Name the project:
4. custom_widgets
5. Choose your lab folder.
6. Wait for setup completion.

Step 2: Write the Program

1. Open:
2. lib → [Link]
3. Delete existing code.
4. Copy and paste the following code.

37
UI Flutter

Program: Custom Widgets Example

38
UI Flutter

Step 3: Run the Program


1. Open View → Terminal.
2. Type:
3. flutter run
4. Select Chrome or Windows device.

Step 4: Observe the Output


 Displays three custom text fields for Name, Email, and Roll Number.
 A custom “Press Me” button is displayed below them.
 Text entered triggers print messages in the debug console.
 Button click also shows output in the console.

39
UI Flutter

(b): Apply Styling Using Themes and Custom Styles

Objective:
To apply themes and custom styles in Flutter for a consistent and visually appealing user
interface.

Theory:
Themes in Flutter allow developers to define global styles for widgets, colors, text, and
buttons.
This helps maintain a consistent visual identity across the app.

Key Styling Components:

 ThemeData: Defines the color scheme, text styles, and button themes.
 TextTheme: Defines font styles for headings, body text, etc.
 ElevatedButtonThemeData: Used to style all elevated buttons uniformly.
 [Link](context): Used to access and apply theme data in widgets.

Procedure:
Step 1: Create a New Flutter Project

1. Open VS Code → View → Command Palette...


2. Select Flutter: New Project → Application.
3. Name the project:
4. Styling_Example
5. Choose your main lab folder and wait for setup.

Step 2: Write the Program

1. Open:
2. lib → [Link]
3. Delete existing code and paste the program below.

40
UI Flutter

Program: Apply Styling Using ThemeData

41
UI Flutter

Step 3: Run the Program


1. Open View → Terminal → Type:
2. flutter run
3. Select device (Chrome/Windows).
4. Wait for the app to open.

Step 4: Observe the Output


Output Description:

 The app bar displays the title “Styling Example.”


 The text “Welcome to MyApp” appears using custom theme styling.
 The “Get Started” button is styled with rounded corners, padding, and custom font
size.

42
UI Flutter

Lab Session 7
Working with Forms

a) Design a Form with Various Input Fields


Objective:

To design and implement a Flutter form containing multiple input fields such as text fields,
checkboxes, radio buttons, and dropdown menus.

Software Requirements:

 Flutter SDK
 Visual Studio Code (VS Code)
 Chrome / Android Emulator

Theory:

A Form in Flutter is used to collect user input from multiple fields together.
Widgets such as TextFormField, Checkbox, Radio, and DropdownButton can be grouped inside a
Form widget.

The GlobalKey<FormState> is used to uniquely identify the form and manage validation and
submission.
User interactions are handled using setState() to refresh the UI dynamically whenever a value
changes.

Procedure:

Step 1: Create a New Flutter Project

1. Open Visual Studio Code.


2. Go to View → Command Palette... or press Ctrl + Shift + P.
3. Select Flutter: New Project → Application.
4. Enter the project name as:
5. Form_Example
6. Choose your folder (e.g., Documents → Ayesha_23031F0012).
7. Wait until the message “All done! Your Flutter app is ready.” appears.

Step 2: Write the Program

1. Open your project folder in VS Code.


2. In the Explorer panel, open the file:
3. lib → [Link]
4. Delete any existing code.
5. Copy and paste the below code.
6. Save the file (Ctrl + S).

43
UI Flutter

Program: Form with Various Input Fields

import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Form Example',
theme: ThemeData(primarySwatch: [Link]),
home: FormPage(),
);
}
}

class FormPage extends StatefulWidget {


@override
_FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {


final _formKey = GlobalKey<FormState>();
String? _name;
String? _email;
bool _subscribeToNewsletter = false;
String _selectedCountry = 'USA';
String _gender = 'Male';

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Form Example')),
body: Padding(
padding: [Link](20.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
onSaved: (value) {
_name = value;

44
UI Flutter

},
),
SizedBox(height: 20),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
onSaved: (value) {
_email = value;
},
),
SizedBox(height: 20),
Row(
children: <Widget>[
Checkbox(
value: _subscribeToNewsletter,
onChanged: (value) {
setState(() {
_subscribeToNewsletter = value!;
});
},
),
Text('Subscribe to Newsletter'),
],
),
SizedBox(height: 20),
Row(
children: <Widget>[
Text('Gender: '),
Radio<String>(
value: 'Male',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
Text('Male'),
Radio<String>(
value: 'Female',
groupValue: _gender,
onChanged: (value) {
setState(() {
_gender = value!;
});
},
),
Text('Female'),
],
),

45
UI Flutter

SizedBox(height: 20),
Row(
children: <Widget>[
Text('Country: '),
SizedBox(width: 20),
DropdownButton<String>(
value: _selectedCountry,
onChanged: (value) {
setState(() {
_selectedCountry = value!;
});
},
items: <String>['USA', 'Canada', 'UK', 'Australia']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
),
],
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_formKey.currentState!.save();
print('Name: $_name');
print('Email: $_email');
print('Gender: $_gender');
print('Subscribe: $_subscribeToNewsletter');
print('Country: $_selectedCountry');
},
child: Text('Submit'),
),
],
),
),
),
),
);
}
}

Step 3: Run the Program

46
UI Flutter

1. Open View → Terminal or press Ctrl + `.


2. In the terminal, type:
3. flutter run
4. Choose the device (e.g., Chrome or Windows).
5. Wait for the project to build and display output.

Output:

✅ The app displays a form with the following fields:

 Name (Text Field)


 Email (Text Field)
 Gender (Radio Buttons)
 Subscribe to Newsletter (Checkbox)
 Country (Dropdown)
 Submit Button

🖱️ On pressing Submit, entered data is printed in the console.

47
UI Flutter

b) Implement Form Validation and Error Handling


Objective:

To apply validation and error handling in Flutter forms using TextFormField validators.

Theory:

Validation ensures that user inputs meet certain conditions before being accepted.
In Flutter, the validator property of a TextFormField is used to display an error message when a
field is invalid.
The [Link]() method checks all fields, and [Link]() saves valid input values.

Procedure:

Step 1: Open Your Project

1. Open your existing project in VS Code.


2. Go to lib → [Link].
3. Replace your existing code with the below validation example.
4. Save the file.

Step 2: Run the Program

1. Open the terminal (View → Terminal).


2. Type:
3. flutter run
4. Observe validation messages and results.

48
UI Flutter

Program: Form Validation Example

import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Form Example')),
body: SingleChildScrollView(
padding: [Link](16),
child: FormWidget(),
),
),
);
}
}

class FormWidget extends StatefulWidget {


@override
_FormWidgetState createState() => _FormWidgetState();
}

class _FormWidgetState extends State<FormWidget> {


final _formKey = GlobalKey<FormState>();

// ✅ Nullable variables to avoid initialization error


String? _name;
String? _email;
String? _password;
String? _phone;
String? _address;

@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'),

49
UI Flutter

validator: (value) {
if (value == null || [Link]) {
return 'Please enter your name';
}
return null;
},
onSaved: (value) => _name = value,
),
SizedBox(height: 16),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
keyboardType: [Link],
validator: (value) {
if (value == null || [Link]) {
return 'Please enter your email';
}
return null;
},
onSaved: (value) => _email = value,
),
SizedBox(height: 16),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) {
if (value == null || [Link]) {
return 'Please enter a password';
}
return null;
},
onSaved: (value) => _password = value,
),
SizedBox(height: 16),
TextFormField(
decoration: InputDecoration(labelText: 'Phone'),
keyboardType: [Link],
validator: (value) {
if (value == null || [Link]) {
return 'Please enter your phone number';
}
return null;
},
onSaved: (value) => _phone = value,
),
SizedBox(height: 16),
TextFormField(
decoration: InputDecoration(labelText: 'Address'),
maxLines: 3,
validator: (value) {

50
UI Flutter

if (value == null || [Link]) {


return 'Please enter your address';
}
return null;
},
onSaved: (value) => _address = value,
),
SizedBox(height: 16),
ElevatedButton(onPressed: _submitForm, child: Text('Submit')),
],
),
);
}

void _submitForm() {
// ✅ Added null-safe operator
if (_formKey.currentState?.validate() ?? false) {
_formKey.currentState?.save();
// Print results
print('Form submitted:');
print('Name: $_name');
print('Email: $_email');
print('Password: $_password');
print('Phone: $_phone');
print('Address: $_address');
}
}
}

51
UI Flutter

Output:

✅ Error messages appear under each field if left blank.


✅ When all inputs are valid and submitted, a snackbar message “Form Submitted
Successfully!” is shown, and entered details print in the console.

52
UI Flutter

Lab Session 8

a) Add Animations to UI Elements Using Flutter’s


Animation Framework
Aim:

To create and apply basic animations to Flutter UI elements using the AnimationController
and Tween classes.

Objective:

1. To learn how to animate widgets in Flutter.


2. To use AnimationController for controlling animation timing.
3. To use Tween to define the start and end points of the animation.
4. To rebuild the widget tree dynamically with animation updates.

Theory:

In Flutter, animations bring UI elements to life by providing smooth transitions between


different states.

 AnimationController manages the duration and control of an animation.


 Tween defines the range of animated values.
 addListener() updates the state whenever the animation value changes.
 setState() is used to rebuild the widget tree with new values.

Steps to Execute:

1. Open Visual Studio Code.


2. Click View → Command Palette → type Flutter: New Project → select
Application.
3. Enter project name as flutter_animations.
4. Save the project inside your folder .
5. Wait until project setup completes.
6. Open the lib folder → open [Link].
7. Delete the existing code in [Link].
8. Copy and paste the following program.
9. Save the file (Ctrl + S).
10. Run the app using the command:
11. flutter run
12. Choose Chrome (2) or Windows (1) device.

53
UI Flutter

Program:

import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Animation Example')),
body: AnimationWidget(),
),
);
}
}

class AnimationWidget extends StatefulWidget {


@override
_AnimationWidgetState createState() => _AnimationWidgetState();
}

class _AnimationWidgetState extends State<AnimationWidget>


with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;

@override
void initState() {
[Link]();
_controller = AnimationController(
duration: Duration(seconds: 1),
vsync: this,
);

_animation = Tween<double>(begin: 0, end: 300).animate(_controller)


..addListener(() {
setState(() {});
});
}

@override
Widget build(BuildContext context) {
return Center(
child: Column(

54
UI Flutter

mainAxisAlignment: [Link],
children: <Widget>[
Container(
width: _animation.value,
height: _animation.value,
color: [Link],
child: FlutterLogo(size: 100),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
if (_controller.status == [Link]) {
_controller.reverse();
} else {
_controller.forward();
}
},
child: Text(
_controller.status == [Link]
? 'Reverse Animation'
: 'Start Animation',
),
),
],
),
);
}

@override
void dispose() {
_controller.dispose();
[Link]();
}
}

Output:

A blue square containing the Flutter logo grows and shrinks smoothly when the button is
pressed.

55
UI Flutter

56
UI Flutter

b): Experiment with Different Types of Animations (Fade, Slide,


Scale)
Aim:

To implement and compare different types of animations such as Fade, Slide, and Scale
using Flutter’s animation framework.

Objective:

1. To apply multiple types of animations in a single Flutter app.


2. To learn how to use FadeTransition, SlideTransition, and ScaleTransition widgets.
3. To use AnimationController and Tween for controlling animation timing and
behavior.

Theory:

Flutter provides prebuilt transition widgets for easy animations:

 FadeTransition → changes the opacity (transparency).


 SlideTransition → moves a widget from one position to another.
 ScaleTransition → grows or shrinks the size of a widget.

Each of these uses:

 AnimationController → controls duration, direction.


 Tween → defines the animation range.
 Animation → stores current animation value.

Steps to Execute:

1. Open Visual Studio Code.


2. Go to View → Command Palette → Flutter: New Project → Application.
3. Name the project animation_types.
4. Save it inside your Flutter folder .
5. Wait for project creation to finish.
6. Open the lib folder → open [Link].
7. Delete the default code.
8. Copy and paste the below combined code.
9. Save the file (Ctrl + S).
10. Run in terminal using:

flutter run

11. Select Chrome (2) or Windows (1).

57
UI Flutter

Program:

import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Different Types of Animations',
theme: ThemeData(primarySwatch: [Link]),
home: AnimationDemo(),
);
}
}

class AnimationDemo extends StatefulWidget {


@override
_AnimationDemoState createState() => _AnimationDemoState();
}

class _AnimationDemoState extends State<AnimationDemo>


with TickerProviderStateMixin {
// Controllers for different animations
late AnimationController _fadeController;
late AnimationController _slideController;
late AnimationController _scaleController;

// Animation variables
late Animation<double> _fadeAnimation;
late Animation<Offset> _slideAnimation;
late Animation<double> _scaleAnimation;

@override
void initState() {
[Link]();

// Fade Animation
_fadeController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_fadeAnimation = Tween<double>(
begin: 0.0,
end: 1.0,

58
UI Flutter

).animate(_fadeController);
_fadeController.forward();

// Slide Animation
_slideController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_slideAnimation = Tween<Offset>(
begin: Offset(-1.0, 0.0),
end: Offset(0.0, 0.0),
).animate(_slideController);
_slideController.forward();

// Scale Animation
_scaleController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_scaleAnimation = Tween<double>(
begin: 0.0,
end: 1.0,
).animate(_scaleController);
_scaleController.forward();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Fade, Slide, and Scale Animations')),
body: SingleChildScrollView(
child: Padding(
padding: const [Link](20),
child: Column(
mainAxisAlignment: [Link],
children: [
// Fade Animation
Text(
'Fade Animation',
style: TextStyle(fontSize: 20, fontWeight: [Link]),
),
FadeTransition(
opacity: _fadeAnimation,
child: Container(width: 150, height: 150, color: [Link]),
),
SizedBox(height: 40),

// Slide Animation
Text(

59
UI Flutter

'Slide Animation',
style: TextStyle(fontSize: 20, fontWeight: [Link]),
),
SlideTransition(
position: _slideAnimation,
child: Container(width: 150, height: 150, color:
[Link]),
),
SizedBox(height: 40),

// Scale Animation
Text(
'Scale Animation',
style: TextStyle(fontSize: 20, fontWeight: [Link]),
),
ScaleTransition(
scale: _scaleAnimation,
child: Container(width: 150, height: 150, color:
[Link]),
),
],
),
),
),
);
}

@override
void dispose() {
_fadeController.dispose();
_slideController.dispose();
_scaleController.dispose();
[Link]();
}
}

60
UI Flutter

Output:

The app displays three boxes demonstrating different animations:

1. Blue box fades in gradually.


2. Green box slides in from the left.
3. Orange box scales up from small to full size.

61
UI Flutter

Lab Session 9
a) Fetch Data from REST API

Objective:

To fetch data from a REST API and display it dynamically in a Flutter web application.

Instructions:

1. Create a New Flutter Project


o Open Visual Studio Code.
o Go to View → Command Palette → Flutter: New Project.
o Choose Application.
o Enter project name: api_fetch_example.
o Save it inside your folder in Documents.
2. Add HTTP Package
o Open [Link] file.
o Under dependencies:, add:
o http: ^0.13.3
o Save the file (Ctrl + S).
o Then open Terminal in VS Code and run:
oflutter pub get
3. Open lib/[Link]
o Delete any existing code.
o Copy and paste the following program.

Program:

import 'dart:convert';
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}

class HomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();

62
UI Flutter

class _HomePageState extends State<HomePage> {


List<dynamic> _data = [];

@override
void initState() {
[Link]();
_fetchDataFromApi();
}

Future<void> _fetchDataFromApi() async {


final response = await [Link](
[Link]('[Link]
);

if ([Link] == 200) {
setState(() {
_data = [Link]([Link]);
});
} else {
throw Exception('Failed to load data');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Data Example')),
body: [Link](
itemCount: _data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_data[index]['title']),
subtitle: Text(_data[index]['body']),
);
},
),
);
}
}

63
UI Flutter

Execution Steps:

1. Open View → Terminal in VS Code.


2. Type:
3. flutter run
4. When asked to choose a device, type 2 for Chrome.
5. The app will launch in a browser showing data fetched from the REST API.

Output:

A scrollable list appears in the browser window displaying:

 Post Titles
 Post Descriptions

Data is fetched live from:

[Link]

64
UI Flutter

(b): Display the Fetched Data in a Meaningful Way in the


UI
Objective:

To display the fetched data from a REST API in a structured and user-friendly layout using
Flutter widgets such as Cards and ListView.

Instructions:

1. Use the Same Project


o Continue using the previous project:
api_fetch_example
2. Open lib/[Link]
o Delete the old code and replace it with the following updated program.
3. Save the File
o Press Ctrl + S after pasting the code.
4. Run the Program
o Open View → Terminal and type:
o flutter run
o Choose Chrome (2) when prompted.

Program:

import 'dart:convert';
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage(), debugShowCheckedModeBanner: false);
}
}

class HomePage extends StatefulWidget {


@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


List<dynamic> _data = [];
bool _isLoading = false;

65
UI Flutter

@override
void initState() {
[Link]();
_fetchDataFromApi();
}

Future<void> _fetchDataFromApi() async {


setState(() {
_isLoading = true;
});

final response = await [Link](


[Link]('[Link]
);

if ([Link] == 200) {
setState(() {
_data = [Link]([Link]);
_isLoading = false;
});
} else {
throw Exception('Failed to load data');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Data Example')),
body: _isLoading
? Center(child: CircularProgressIndicator())
: [Link](
itemCount: _data.length,
itemBuilder: (context, index) {
return PostCard(
title: _data[index]['title'],
body: _data[index]['body'],
);
},
),
);
}
}

class PostCard extends StatelessWidget {


final String title;
final String body;

const PostCard({Key? key, required [Link], required [Link]})

66
UI Flutter

: super(key: key);

@override
Widget build(BuildContext context) {
return Card(
margin: [Link](horizontal: 16, vertical: 8),
elevation: 4,
child: Padding(
padding: [Link](16),
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
Text(
title,
style: TextStyle(fontSize: 18, fontWeight: [Link]),
),
SizedBox(height: 8),
Text(body, style: TextStyle(fontSize: 16)),
],
),
),
);
}
}

Execution Steps:

1. Save the file in VS Code (Ctrl + S).


2. Run the project using:
3. flutter run
4. Select Chrome as the device.
5. The app will display posts fetched from an online API in card format.

Output:

Shows a CircularProgressIndicator while loading.

Displays each post in a Card layout with:

 Title (bold and large font)


 Description (normal text)
All posts appear in a scrollable ListView.

67
UI Flutter

68
UI Flutter

Lab Session 10

(a) Write Unit Tests for UI Components


Aim

To write and execute widget tests for a Flutter UI component using the flutter_test
package.

Objective

 Learn how to test UI widgets without running the full app.


 Verify if widgets display the right text and styles.
 Practice using flutter test command.

Explanation

 Flutter provides the flutter_test package for unit testing and widget testing.
 We use testWidgets() to check if UI widgets are displaying properly and have
correct styles.
 In this example, we’ll test a PostCard widget which shows a title and body text.

Step-by-Step Procedure

Step 1: Create a new Flutter project (if not done)


flutter create post_card_test_example
Step 2: Create a file for your widget

Path: lib/post_card.dart

code:

import 'package:flutter/[Link]';
import 'package:flutter_test/flutter_test.dart';
import 'package:post_card_test_example/post_card.dart'; // change name if your
project is different

void main() {
// Test 1: Check text display
testWidgets('PostCard displays title and body', (WidgetTester tester) async
{
await [Link](
MaterialApp(
home: Scaffold(
body: PostCard(title: 'Test Title', body: 'Test Body'),
),
),
);

69
UI Flutter

// Check if both texts appear


expect([Link]('Test Title'), findsOneWidget);
expect([Link]('Test Body'), findsOneWidget);
});

// Test 2: Check styling


testWidgets('PostCard has correct text styling', (WidgetTester tester) async
{
await [Link](
MaterialApp(
home: Scaffold(
body: PostCard(title: 'Test Title', body: 'Test Body'),
),
),
);

final titleText = [Link]<Text>([Link]('Test Title'));


expect([Link]?.fontSize, 18);
expect([Link]?.fontWeight, [Link]);

final bodyText = [Link]<Text>([Link]('Test Body'));


expect([Link]?.fontSize, 16);
});
}

Step 3: Create a test file

Path: test/post_card_test.dart

code:

import 'package:flutter/[Link]';
import 'package:flutter_test/flutter_test.dart';
import 'package:post_card_test_example/post_card.dart'; // change name if your
project is different

void main() {
// Test 1: Check text display
testWidgets('PostCard displays title and body', (WidgetTester tester) async
{
await [Link](
MaterialApp(
home: Scaffold(
body: PostCard(title: 'Test Title', body: 'Test Body'),
),
),

70
UI Flutter

);

// Check if both texts appear


expect([Link]('Test Title'), findsOneWidget);
expect([Link]('Test Body'), findsOneWidget);
});

// Test 2: Check styling


testWidgets('PostCard has correct text styling', (WidgetTester tester) async
{
await [Link](
MaterialApp(
home: Scaffold(
body: PostCard(title: 'Test Title', body: 'Test Body'),
),
),
);

final titleText = [Link]<Text>([Link]('Test Title'));


expect([Link]?.fontSize, 18);
expect([Link]?.fontWeight, [Link]);

final bodyText = [Link]<Text>([Link]('Test Body'));


expect([Link]?.fontSize, 16);
});
}

Step 4: Run the test

In VS Code Terminal, type:

flutter test

Expected Output

Test results will appear in the terminal like this:

00:00 +2: All tests passed!

If you purposely change the text or font size in PostCard, the test will fail showing what
went wrong.

Conclusion

71
UI Flutter

 We verified that the PostCard widget correctly displays text and has proper font
styling.
 Widget tests help ensure UI components behave as expected — even before running
the full app.

72
UI Flutter

(b) Use Flutter’s Debugging Tools to Identify and Fix


Issues
Aim

To identify and fix a bug in a Flutter app using debugging tools such as the Widget
Inspector, Debug Console, and Breakpoints.

Problem

In this example, the counter app’s + button does not update the counter on screen because
the setState() function is missing.

Buggy Code

import 'package:flutter/[Link]';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(home: CounterApp());
}
}

class CounterApp extends StatefulWidget {


@override
_CounterAppState createState() => _CounterAppState();
}

class _CounterAppState extends State<CounterApp> {


int _counter = 0;

void _incrementCounter() {
// Bug: Not using setState()
_counter++;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter App')),
body: Center(
child: Column(
mainAxisAlignment: [Link],

73
UI Flutter

children: [
Text('Counter:', style: TextStyle(fontSize: 24)),
Text(
'$_counter',
style: TextStyle(fontSize: 36, fontWeight: [Link]),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon([Link]),
),
);
}
}

Steps to Debug

Step 1: Run in Debug Mode

 Run:
 flutter run
 or press Run → Start Debugging (F5) in VS Code.

Step 2: Open Widget Inspector

 In VS Code, click “Open DevTools” at the top.


 Go to Widget Inspector → Click the + button in your app.
 Confirm the onPressed callback is linked to _incrementCounter.

Step 3: Add Debug Print

Modify the increment method:

void _incrementCounter() {
print('Increment button pressed');
_counter++;
}

Run the app and check the Debug Console.


If nothing prints → the button isn’t working.
If it prints but number doesn’t update → UI is not rebuilding.

74
UI Flutter

Step 4: Set Breakpoints

 Click the left margin beside _incrementCounter() in VS Code.


 Press F5 → Run app → Press + button.
 Code execution stops here; inspect variable values.

Step 5: Fix the Bug

Replace the method with:

void _incrementCounter() {
setState(() {
_counter++;
});
}

Now, when you press the button, the counter increases on screen.

Expected Output

 Counter increments correctly after pressing +.


 Debug console shows:

Increment button pressed

 Breakpoint stops at _incrementCounter() when debugging.

Conclusion

 setState() is essential to refresh UI after a variable changes.


 Widget Inspector helps verify widget connections.
 Debug Console and Breakpoints allow tracking logic flow and variable changes.

75

You might also like