Flutter Lab Manual
Flutter Lab Manual
Flutter Lab Manual
ENGINERING (AI&ML)
UI DESIGN-FLUTTER LAB
Lab Manual
VISION
To become an institute of excellence by creating high quality and innovating engineering and management
professionals who would take the world into their stride through sustainable growth in technolog and
management.
MISSION
To instill moral values and promote technological, intellectual and ethical environment to the students with an
in-depth and exceptional education that makes them employment ready asper the emerging trends in industry
and to invoke the desire of innovation as a process of life- long learning for a successful career in engineering
and management.
VISION
To evolve the department of computer science & engineering as a centre of academicexcellence with latest
technologies to transform students into innovative global leaders.
MISSION
M1: To produce competitive graduates having creative skills and ethical values to succeed intheir fields as well
as the foundation for life-long learning.
M2: By promoting research and development activities in collaboration with reputed industriesand laboratories.
M3: To analyze design, and develop high-quality software systems using the appropriatetheory, principles,
tools and processes.
DEPARTMENT OF COMPUTER SCIENCE & ENGINERING (AI&ML)
Engineeringknowledge:Applytheknowledgeofmathematics,science,engineering
PO1
Fundamentals andanengineeringspecializationtothesolutionofcomplexengineeringproblems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
PO3
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
Conduct investigations of complex problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO7 Solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
PO8
norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader
PO9
In diverse teams, and in multi-disciplinary settings.
Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
PO10
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the
PO11 Engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life-long learning in the broadest context of technological change.
Problem Solving Skills – Graduate will be able to apply computational techniques and
PSO1
software principles to solve complex engineering problems pertaining to software engineering.
Professional Skills – Graduate will be able to think critically, communicate effectively, and
PSO2
collaborate in teams through participation in co and extra-curricular activities.
Successful Career – Graduates will possess a solid foundation in computer science and
PSO3 engineering that will enable them to grow in their profession and pursue lifelong learning
through post-graduation and professional development.
DEPARTMENT OF COMPUTER SCIENCE & ENGINERING (AI&ML)
Course Objectives:
Learns to Implement Flutter Widgets and Layouts
Understands Responsive UI Design and with Navigation in Flutter
Knowledge on Widges and customize widgets for specific UI elements, Themes
Understand to include animation apart from fetching data
Course Outcomes:
Implements Flutter Widgets and Layouts
Responsive UI Design and with Navigation in Flutter
Create custom widgets for specific UI elements and also Apply styling using themes and custom styles.
Design a form with various input fields, along with validation and error handling
Fetches data and write code for unit Test for UI components and also animation
DEPARTMENT OF INFORMATION TECHNOLOGY
Course Name: UI DESIGN-FLUTTER LAB Course Code: AM507PC
Year/Semester: III/I Regulation: R22
FACULTY HOD
1. a) Install Flutter and Dart SDK.
Pre-installation Requirements
Windows 10 operating system installed (Flutter will work on Windows 7 SP1 and later versions).
At least 1.65 GB of free disk space (Additional free storage is needed for other tools and IDEs, if not already installed).
Windows Powershell 5.0 or newer.
Git for Windows version 2.0 or newer (Optional).
Android Studio installed.
Visual Studio 2022 with C++ (Optional).
C:\Users\tomz>flutter doctor
Running "flutter pub get" in flutter_tools... 8,9s
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.10.4, on Microsoft Windows [Version 10.0.19041.746], locale en-US)
[X] Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
'flutter config --android-sdk' to update to that location.
Afterward, Android Studio Setup Wizard will start and you can proceed by clicking Next.
On the Install Type screen, select Custom and click Next.
Select the installation location or leave the default path and click Next.
Select your UI theme and click Next.
On the next screen, accept the License Agreement and click Finish.
The download of the components will start and Android Studio install. Once completed, click Finish.
After the installation, start Android Studio. On the left side, click Plugins. Search for Flutter and click Install to install the
Flutter plugin.
It will also prompt you to install Dart, a programming language used to create Flutter apps. Click Install at the prompt.
Finally, click Restart IDE so that the plugin changes are applied. Click Restart at the prompt to confirm this action.
Afterward, run the flutter doctorcommand in CMD to confirm the Android Studio installation.
C:\Users\tomz>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.10.4, on Microsoft Windows [version 10.0.19041.746), locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++- workload, including all of its default components
[√] Android Studio (version 2021.1)
[√] Connected device (2 available)
[√] HTTP Host Availability
Android Studio was successfully installed, however, it finds an issue with Android licenses. This issue is fairly common
and is mitigated by running the following command in CMD.
Running the flutter doctor command again shows the issue resolved.
C:\Users\tomz>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.10.4, on Microsoft Windows [Version 10.0.19041.746], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
X Visual Studio not installed; this is necessary for Windows development.
Download at https://visualstudio.microsoft.com/downloads/.
Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.1)
[√] Connected device (2 available)
[√] HTTP Host Availability
This is a simple dart program that prints Hello World on screen. Most programmers write the Hello World program as
their first program.
void main() {
print("Hello World!");
}
void main() is the starting point where the execution of your program begins.
Every program starts with a main function.
The curly braces {} represent the beginning and the ending of a block of code.
print(“Hello World!”); prints Hello World! on screen.
Each code statement must end with a semicolon.
void main()
{
var name ="John";
print(name);
}
Here $variableName is used to join variables. This joining process in dart is called string interpolation.
void main(){
var firstName ="John";
var lastName ="Doe";
print("Full name is $firstName $lastName");
}
void main() {
int num1 =10; //declaring number1
int num2 =3; //declaring number2
// Calculation
int sum = num1 + num2;
int diff = num1 - num2;
int mul = num1 * num2;
double div = num1 / num2; // It is double because it outputs number with decimal.
It’s nice to work on a single file, but if your project gets bigger, you need to manage configurations, packages, and assets
files. So creating a dart project will help you to manage this all.
This will create a simple dart project with some ready-made code.
First, open the project location on the command/terminal and run the project with this command.
dart run
Result: Hence we performed simple Dart program to understand the language basics
Text(
'Hello, Flutter!',
style: TextStyle(
fontSize: 20,
color: Colors.blue,
Image: The Image widget is used to display images. You can load images from assets, network, or memory.
fontWeight: FontWeight.bold,
),Container: The Container widget is a versatile widget that allows you to create visual elements with various styling
Image.asset('assets/images/flutter_logo.png'),
), options such as color, padding, margin, border, etc.
Container(
width: 100,
height: 100,
color: Colors.red,
child: Center(
child: Text(
'Container',
style: TextStyle(
color: Colors.white,
Row:), The Row widget arranges its children in a horizontal array. It's useful for creating horizontally aligned layouts.
Row( ),
),
children: [
), Icon(Icons.star),
Text('5.0'),
],
),Column: The Column widget arranges its children in a vertical array. It's useful for creating vertically aligned layouts.
Column(
children: [
Text('First
ListView: The item'),
ListView widget displays a scrollable list of children. It's useful when you have a large number of items to
Text('Second item'), display.
],
ListView(
),
children: [
ListTile(title: Text('Item 1')),
ListTile(title: Text('Item 2')),
ListTile(title: Text('Item 3')),
AppBar:
], The AppBar widget is typically used as the top app bar in a Scaffold. It provides astandard title, leading, and
), actions slots.
AppBar(
title: Text('My App'),
actions:
These[ are just a few examples of the many widgets available in Flutter. Flutter's widget system allows for easy
IconButton(customization and composition, enabling developers to create complex and beautiful UIs efficiently.
icon: Icon(Icons.search),
Result:Thus we perform various Flutter widgets (Text, Image, Container, etc.).
onPressed: ()2.b)
{ Implement different layout structures using Row, Column, and Stack widgets.
// Add search functionality different layout structures using Row, Column, and Stack widgets in Flutter
Aim:Implementing
},
),
], Program:
), import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
This Flutter code creates a simple app with different layout structures:
Row: Three containers aligned horizontally with equal space between them.
Column: Three containers aligned vertically with space between them.
Stack: A container stacked on top of another container with positioning.
Result: Thus we Implementing different layout structures using Row, Column, and Stack widgets in Flutter
3. a) Design a responsive UI that adapts to different screen sizes.
Aim: To design a responsive UI that adapts to different screen sizes in flutter
To design a responsive UI in Flutter that adapts to different screen sizes, you can use Flutter's built-in layout widgets such
as Row, Column, Container, Expanded, Flexible, and MediaQuery. Here's an example of how you can create a responsive
UI in Flutter:
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
The LayoutBuilder widget is used to dynamically choose between different layouts based on the available width.
When the screen width is greater than 600, a wide layout is displayed with content side by side. Otherwise, a narrow
layout is displayed with content stacked vertically.
Depending on the layout, different widgets such as Row, Column, and Container are used to arrange and display
content.
You can adjust the width and height of the containers, as well as other properties, to fit your specific design
requirements.
Result: Thus we designed a responsive UI that adapts to different screen sizes in flutter
In Flutter, you can implement responsiveness using MediaQuery and breakpoints. MediaQuery provides information about
the current app screen such as size and orientation, which you can use to make layout decisions. Breakpoints are specific
screen sizes at which you may want to adjust your layout.
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
Result: Thus we implemented media queries and breakpoints for responsiveness in Flutter
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Navigation Example',
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/second': (context) => SecondScreen(),
},
);
}
}
In Flutter, you can implement navigation with named routes by using the MaterialApp widget and defining a map of named
routes
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
1. Stateful Widgets:
Stateful widgets are dynamic widgets that can change their appearance or behavior over time.
They maintain state, meaning they can hold data and update it when needed, causing the UI to rebuild
accordingly.
Stateful widgets are typically used when the UI elements need to change based on user interactions, data
changes, or other external factors.
They consist of two classes: a StatefulWidget class and a State class.
The StatefulWidget class is immutable and creates an instance of the State class, which manages the
widget's state and controls how it's displayed.
When the state of a stateful widget changes, the build method of the associated State object is called, and the
UI is rebuilt to reflect the new state.
Program:
import 'package:flutter/material.dart';
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter Value:',
style: TextStyle(fontSize: 20.0),
),
Text(
'$_counter',
style: TextStyle(fontSize: 36.0),
),
SizedBox(height: 20.0),
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
),
);
}
}
2. Stateless Widgets:
Stateless widgets, on the other hand, are static widgets that cannot change their state once they are built.
They do not have any internal state and are purely based on the information provided at the time of creation.
Stateless widgets are used for UI elements that do not need to change, such as static text, icons, buttons, etc.
Since they do not have any state, they are more efficient and lightweight compared to stateful widgets.
Stateless widgets are implemented using a single StatelessWidget class, and they typically have a build
method that returns the UI components.
Once a stateless widget is built, it remains the same until it's rebuilt explicitly by calling the setState method
or when its parent widget is rebuilt.
Program:
import 'package:flutter/material.dart';
To create custom widgets for specific UI elements in Flutter, you can follow these steps:
Identify the UI Element: Determine the specific UI element for which you want to create a custom widget. For
example, let's say you want to create a custom button.
Create a Stateless or Stateful Widget: Depending on the complexity and interactivity of the UI element, decide
whether to create a StatelessWidget or a StatefulWidget.
Implement the Widget: Implement the custom widget by extending StatelessWidget or StatefulWidget. Define its
appearance and behavior as required.
Customize Properties: Expose parameters (also known as props or properties) that allow users of the custom widget
to customize its appearance or behavior.
Use the Custom Widget: Finally, utilize the custom widget in your app wherever necessary.
Program
import 'package:flutter/material.dart';
const CustomButton({
Key? key,
required this.text,
required this.onPressed,
this.color = Colors.blue,
this.textColor = Colors.white,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
style: ElevatedButton.styleFrom(
primary: color,
),
child: Text(
text,
style: TextStyle(
color: textColor,
),
),
);
}
}
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
Result: Thus we applied styling using themes and custom styles in flutter
void main() {
runApp(MyApp());
}
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your name';
}
return null;
},
onChanged: (value) {
setState(() {
_name = value;
});
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
return null;
},
onChanged: (value) {
setState(() {
_email = value;
});
},
),
TextFormField(
obscureText: true,
decoration: InputDecoration(labelText: 'Password'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
return null;
},
onChanged: (value) {
setState(() {
_password = value;
});
},
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Form is valid!'),
),
);
// Perform operations with form data here
// For example: send data to server, etc.
}
},
child: Text('Submit'),
),
),
],
),
),
);
}
}
b) Implement form validation and error handling.
In Flutter, you can implement form validation and error handling using the Form widget along with TextFormField widgets
for input fields.
import 'package:flutter/material.dart';
Program:
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextFormField(
controller: _nameController,
validator: (value) {
if (value.isEmpty) {
return 'Please enter your name';
}
return null;
},
decoration: InputDecoration(
labelText: 'Name',
),
),
TextFormField(
controller: _emailController,
validator: (value) {
if (value.isEmpty) {
return 'Please enter your email';
}
// You can add more complex validation for email here
return null;
},
decoration: InputDecoration(
labelText: 'Email',
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: ElevatedButton(
onPressed: () {
if (_formKey.currentState.validate()) {
// If the form is valid, proceed with submission
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Form submitted')));
// Add your submission logic here
}
},
child: Text('Submit'),
),
),
],
),
),
);
}
@override
void dispose() {
// Clean up the controller when the widget is removed from the widget tree
_nameController.dispose();
_emailController.dispose();
super.dispose();
}
}
Program
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
void initState() {
super.initState();
// Define animation
_animation = Tween<double>(
begin: 0.0,
end: 1.0,
).animate(_animationController);
@override
void dispose() {
// Dispose of the animation controller when the widget is removed from the tree
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Animation Example'),
),
body: Center(
child: AnimatedBuilder(
animation: _animationController,
builder: (context, child) {
return Opacity(
opacity: _animation.value, // Opacity changes from 0.0 to 1.0
child: Container(
width: 200,
height: 200,
color: Colors.blue,
child: Center(
child: Text(
'Animated Text',
style: TextStyle(
fontSize: 20.0,
color: Colors.white,
),
),
),
),
);
},
),
),
);
}
}
void main() {
runApp(MyApp());
}
void toggleVisibility() {
setState(() {
_isVisible = !_isVisible;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animation Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedOpacity(
duration: Duration(seconds: 1),
opacity: _isVisible ? 1.0 : 0.0,
child: Text(
'Fade Animation',
style: TextStyle(fontSize: 24.0),
),
),
SizedBox(height: 20),
AnimatedContainer(
duration: Duration(seconds: 1),
height: _isVisible ? 100.0 : 0.0,
curve: Curves.easeInOut,
child: SlideTransition(
position: Tween<Offset>(
begin: Offset(0, -1),
end: Offset.zero,
).animate(CurvedAnimation(
parent: ModalRoute.of(context).animation!,
curve: Curves.easeInOut,
)),
child: Container(
color: Colors.blue,
child: Center(
child: Text(
'Slide Animation',
style: TextStyle(fontSize: 24.0, color: Colors.white),
),
),
),
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: toggleVisibility,
child: Icon(Icons.play_arrow),
),
);
}
}
Program
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
@override
void initState() {
super.initState();
fetchData();
}
if (response.statusCode == 200) {
setState(() {
_data = json.decode(response.body);
});
} else {
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('REST API Data'),
),
body: _data.isEmpty
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(_data[index]['title']),
subtitle: Text(_data[index]['description']),
);
},
),
),
);
}
}
void main() {
runApp(MyApp());
}
@override
void initState() {
super.initState();
fetchData(); // Function to fetch data
}
void fetchData() {
// Assume fetching data from an API or database
// For example, you can populate fetchedData with dummy data
setState(() {
fetchedData = [
"Item 1",
"Item 2",
"Item 3",
];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetched Data Display'),
),
body: ListView.builder(
itemCount: fetchedData.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(fetchedData[index]),
);
},
),
);
}
}
Program
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(text),
);
}
}
Flutter provides a set of powerful debugging tools to identify and fix issues in your app. Here's a general process you can
follow:
1. Inspect Widgets: Flutter's built-in widget inspector allows you to visualize the widget hierarchy and properties. You
can enable this by pressing the "Toggle Widget Inspector" button in the debug toolbar, or by pressing Ctrl + Alt +
Shift + D (on Windows/Linux) or Cmd + Option + Shift + D (on macOS) in your IDE.
2. Debug Paint: You can enable debug paint mode to see the layout boundaries and padding of each widget. This helps
identify layout issues. Press the "Toggle Debug Paint" button in the debug toolbar or use the shortcut Ctrl + Alt + P
(on Windows/Linux) or Cmd + Option + P (on macOS).
3. Debug Console: Use the debug console to print debug messages and inspect variable values. You can use print()
statements to log messages to the console. Additionally, you can use the debugPrint() function for more controlled
logging.
4. Flutter DevTools: Flutter DevTools is a suite of performance and debugging tools. You can run it by executing the
flutter pub global run devtools command in your terminal and then navigating to the provided URL in your browser.
DevTools provides insights into performance issues, memory usage, widget inspector, and more.
5. Flutter Inspector: This tool, available within the DevTools suite, provides a detailed view of your widget hierarchy
and their properties. You can inspect widgets, view their constraints, and check for layout issues.
6. Hot Reload and Hot Restart: Utilize hot reload (R in the terminal or IDE) and hot restart (Shift + R in the terminal
or IDE) to quickly see the effect of code changes. Hot reload updates the UI state while preserving the app's state,
whereas hot restart resets the app's state.
7. Debugging in IDE: If you're using an IDE like VS Code or Android Studio, take advantage of their debugging
capabilities. Set breakpoints, step through code, and inspect variables to identify and fix issues.
By leveraging these debugging tools effectively, you can efficiently identify and resolve issues in your Flutter app.