Flutter Installation and Layout Guide
Flutter Installation and Layout Guide
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
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: 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:
Image: Widget for displaying images from various sources, including assets,
network URLs, and memory.
Icon: Displays a Material Design icon.
Navigation Widgets:
Animation 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.
5
UI Flutter
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
6
UI Flutter
7
UI Flutter
Note:
The [Link] file is the starting point of every Flutter app.
It contains the main() function that launches the app using runApp().
Steps:
8
UI Flutter
9
UI Flutter
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:
Description of Files
[Link] Entry point of the Flutter app. Contains the layout selector menu.
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
17
UI Flutter
Program:
18
UI Flutter
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.
Concept:
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.”
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:
23
UI Flutter
Output:
Result:
The Flutter application successfully demonstrates navigation between two screens using
[Link]() and [Link]() methods.
24
UI Flutter
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).
Using named routes makes navigation more readable and easier to manage in large
applications.
Procedure:
Step 1: Create a New Flutter Project
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
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
30
UI Flutter
Program:
31
UI Flutter
Output Description:
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
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
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
33
UI Flutter
34
UI Flutter
35
UI Flutter
Action Result
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:
Procedure:
Step 1: Create a New Flutter Project
1. Open:
2. lib → [Link]
3. Delete existing code.
4. Copy and paste the following code.
37
UI Flutter
38
UI Flutter
39
UI Flutter
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.
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:
2. lib → [Link]
3. Delete existing code and paste the program below.
40
UI Flutter
41
UI Flutter
42
UI Flutter
Lab Session 7
Working with Forms
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:
43
UI Flutter
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@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'),
),
],
),
),
),
),
);
}
}
46
UI Flutter
Output:
47
UI Flutter
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:
48
UI Flutter
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@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
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:
52
UI Flutter
Lab Session 8
To create and apply basic animations to Flutter UI elements using the AnimationController
and Tween classes.
Objective:
Theory:
Steps to Execute:
53
UI Flutter
Program:
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@override
void initState() {
[Link]();
_controller = AnimationController(
duration: Duration(seconds: 1),
vsync: this,
);
@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
To implement and compare different types of animations such as Fade, Slide, and Scale
using Flutter’s animation framework.
Objective:
Theory:
Steps to Execute:
flutter run
57
UI Flutter
Program:
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
// 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:
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:
Program:
import 'dart:convert';
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;
void main() {
runApp(MyApp());
}
62
UI Flutter
@override
void initState() {
[Link]();
_fetchDataFromApi();
}
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:
Output:
Post Titles
Post Descriptions
[Link]
64
UI Flutter
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:
Program:
import 'dart:convert';
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;
void main() {
runApp(MyApp());
}
65
UI Flutter
@override
void initState() {
[Link]();
_fetchDataFromApi();
}
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'],
);
},
),
);
}
}
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:
Output:
67
UI Flutter
68
UI Flutter
Lab Session 10
To write and execute widget tests for a Flutter UI component using the flutter_test
package.
Objective
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
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
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
);
flutter test
Expected Output
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
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());
}
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
Run:
flutter run
or press Run → Start Debugging (F5) in VS Code.
void _incrementCounter() {
print('Increment button pressed');
_counter++;
}
74
UI Flutter
void _incrementCounter() {
setState(() {
_counter++;
});
}
Now, when you press the button, the counter increases on screen.
Expected Output
Conclusion
75