Flutter Manual - Compress 9 62
Flutter Manual - Compress 9 62
UI DESIGN-FLUTTER LAB
LAB MANUAL
Week - 2:
3. a) Design a responsive UI that adapts to different screen sizes.
b) Implement media queries and breakpoints for responsiveness.
Week - 3:
5. a) Learn about stateful and stateless widgets.
b) Implement state management using set State and Provider.
Week - 4:
TEXT BOOKS:
1. Marco L. Napoli, Beginning Flutter: A Hands-on Guide to App Development
Course Objectives: To learn
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: After learning the contents of this course the student is able to
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
CO - PO MAPPING:
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
Python CO1 2 1 3 1 2 3
Programming
CO2 1 3 2 2 1 2
Lab
CO3 1 3 2 1 1 2
CO - PSO MAPPING:
PSO-1 PSO-2
CO1 2 2
CO2 1 2
CO3 3 2
WEEK-1
EXPERIMENT NO: 1.
Write code for a simple user registration form for an event.
1. a) Install Flutter and Dart SDK.
Dart SDK is a pre-compiled version so we have to download and extract it only. For this
follow the below-given instructions: Step 1: Download Dart SDK. Download Dart SDK from the
Dart SDK archive page.
The URL is: https://dart.dev/tools/sdk/archive
Click on DART SDK to download SDK for Windows 64-Bit Architecture. The download will start and a
zip file will be downloaded. Note: To download SDK for any other OS select OS of your choice. Step 2:
Extract the downloaded zip file. Extract the contents of downloaded zip file and after extracting contents
of zip file will be as shown:
Step 3: Running Dart. Now open bin folder and type “cmd” as given below:
Command Prompt will open with our desired path of bin folder and now type dart”.
And now we are ready to use dart through bin folder but setting up the path in environment variables will
ease our task of Step3 and we can run dart from anywhere in the file system using command prompt.
Step 4: Setting up path in environment variables. Open Environment Variables from advanced system
settings and add Path in System Variables as depicted in image:
Now we are done to use Dart from anywhere in the file system.
Step 5: Run Dart Using cmd
b) Write a simple Dart program to understand the language basics.
Ans)
Output:
The sum is 13
The diff is 7
The mul is 30
The div is 3.3333333333333335
import 'dart:io';
EXPERIMENT NO: 2.
2. a) Explore various Flutter widgets (Text, Image, Container, etc.).
Text Widget:
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context) { return MaterialApp(
home: Scaffold( backgroundColor: Colors.lightGreen,
appBar: AppBar( backgroundColor: Colors.green,
title: const Text("welcome Screen"),
), // AppBar body: Container( child:
const Center( child: Text("Hello
world!!"),
), // Center
), // Container
), // Scaffold
); // MaterialApp
}
}
Output: Hello World!!
Image Widget:
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context) { return
MaterialApp( home: Scaffold( appBar:
AppBar( title: const Text(
'Insert Image Demo',
),
),
body: Center( child: Column( children:
<Widget>[
Image.asset('assets/images/output.gif', height: 200,
scale: 2.5,
// color: Color.fromARGB(255, 15, 147, 59), opacity:
const
AlwaysStoppedAnimation<double>(0.5)), //Image.asset
Image.asset(
'assets/images/geeksforgeeks.jpg', height: 400,
width: 400,
), // Image.asset
], //<Widget>[]
), //Column
), //Center
),
);
}
}
Containter Widget:
runApp(const MyApp());
Output:
2b) Implement different layout structures using Row, Column, and Stack widgets Row Widget
StatelessWidget {
@override
);
}
}
@override
@override
Row Example"),
),
MainAxisAlignment.spaceEvenly, children:<Widget>[
padding: EdgeInsets.all(8.0),
decoration:BoxDecoration( borderRadius:BorderRadius.circular(8),
color:Colors.green
), child:
Text("React.js",style: TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
Container( margin:
EdgeInsets.all(15.0), padding:
EdgeInsets.all(8.0),
decoration:BoxDecoration( borderRadius
:BorderRadius.circular(8),
color:Colors.green
),
child: Text("Flutter",style:
TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
borderRadius:BorderRadius.circular(8),
color:Colors.green
),
child: Text("MySQL",style:
TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
);
}
Output:
Column Widget:
import 'package:flutter/material.dart';
Stack Widget:
import 'package:flutter/material.dart';
void main() { runApp(MaterialApp( home: Scaffold( appBar:
AppBar( title: Text('GeeksforGeeks'),
backgroundColor: Colors.greenAccent[400],
), //AppBar body: Center( child: SizedBox( width: 300,
height: 300, child: Center( child: Stack( children:
<Widget>[ Container( width: 300, height: 300, color:
Colors.red,
), //Container Container( width:
250, height: 250, color:
Colors.black,
), //Container
Container( height: 200, width:
200, color: Colors.purple,
), //Container
], //<Widget>[]
), //Stack
), //Center
), //SizedBox
) //Center
) //Scaffold
) //MaterialApp
);
}
Output:
WEEK-2
EXPERIMENT NO: 3.
Ans)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <title>Responsive
UI Example</title>
</head>
<body>
<div class="container">
<header class="jumbotron text-center">
<h1>Responsive UI Example</h1>
</header>
<main>
<section class="mb-4">
<h2>Section 1</h2>
<p>This is some content for section 1.</p> </section>
<section class="mb-4">
<h2>Section 2</h2>
<p>This is some content for section 2.</p>
</section>
</main>
Output:
header {
background-color: #333; color:
#fff; text-align:
center; padding: 1em;
}
main { max-width:
1200px; margin: 0 auto;
padding: 20px;
}
section {
margin-bottom: 20px;
} footer
{ background-color:
text- align:
center;
padding: 1em;
position: fixed;
bottom: 0;
width: 100%;
}
footer { position:
static;
}
}
</style>
<title>Responsive UI Example</title>
</head>
<body>
<div class="container">
<header class="jumbotron text-center">
<h1>Responsive UI Example</h1>
</header>
<main>
<section class="mb-4">
<h2>Section 1</h2>
<p>This is some content for section 1.</p>
</section>
<section class="mb-4">
<h2>Section 2</h2>
<p>This is some content for section 2.</p>
</section>
</main>
Output:
EXPERIMENT NO: 4.
Ans)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Screen Navigation Example</title>
<style>
body {
font-family: Arial, sans-
serif; margin: 0; padding: 0;
background-color: #f4f4f4;
}
header {
background-color: #333; color:
#fff; text-align: center;
padding: 1em;
}
main { max-width:
1200px; margin: 0 auto;
padding: 20px;
}
section { display:
none;
}
footer { background-color:
#333; color: #fff; text-align: center;
padding: 1em; position: fixed;
bottom: 0;
width: 100%;
}
<main>
<section id="home" class="active">
<h2>Home Screen</h2>
<p>Welcome to the Home Screen.</p>
<button onclick="navigateTo('about')">Go to About</button> </section>
<section id="about">
<h2>About Screen</h2>
<p>This is the About Screen.</p>
<button onclick="navigateTo('home')">Go to Home</button>
</section>
</main>
<footer class="bg-dark text-light text-center py-3 mt-5"> © 2024 Your Company Name
</footer>
<script>
function navigateTo(screenId) { // Hide
all sections
document.querySelectorAll('section').forEach(section => {
section.classList.remove('active');
});
Output:
Ans)
import 'package:flutter/material.dart';
void main()
{ runApp(MyApp()); }
import 'package:flutter/material.dart';
void main()
{ runApp(MyApp()); }
void incrementCounter()
{ setState(() {
counter++;
}); }
@override
Widget build(BuildContext context) {
return Scaffold( appBar: AppBar(
title: Text('Stateful and Stateless Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[ CounterDisplay(counter),
SizedBox(height: 20),
CounterButton(incrementCounter),
],
),
);
}
}
CounterDisplay(this.count);
@override
Widget build(BuildContext context) {
return Text(
'Counter Value: $count',
style: TextStyle(fontSize:
20),
);
}
}
CounterButton(this.onPressed);
@override
Widget build(BuildContext context) { return
ElevatedButton( onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}
Output:
5 b) Implement state management using set State and Provider.
Output:
EXPERIMENT NO: 6
Output:
Ans)
@override
Widget build(BuildContext context) { const appName =
'Custom Themes';
return MaterialApp( title:
appName, theme: ThemeData(
useMaterial3: true,
// Define the default `TextTheme`. Use this to specify the default // text styling
for headlines, titles, bodies of text, and more.
textTheme: TextTheme( displayLarge:
const TextStyle( fontSize: 72,
fontWeight: FontWeight.bold,
),
// TRY THIS: Change one of the GoogleFonts // to
"lato", "poppins", or "lora".
// The title uses "titleLarge"
// and the middle text uses
"bodyMedium". titleLarge: GoogleFonts.oswald(
fontSize: 30,
fontStyle: FontStyle.italic,
),
bodyMedium: GoogleFonts.merriweather(), displaySmall:
GoogleFonts.pacifico(),
),
),
home: const MyHomePage( title:
appName,
),
);
}
}
this.title});
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text(title,
style: Theme.of(context).textTheme.titleLarge!.copyWith(
color: Theme.of(context).colorScheme.onSecondary,
)),
backgroundColor: Theme.of(context).colorScheme.secondary,
),
body: Center( child:
Container(
padding: const
EdgeInsets.symmetric( horizontal: 12,
vertical: 12,
),
color: Theme.of(context).colorScheme.primary, child: Text(
'Text with a background color',
// TRY THIS: Change the Text value
// or change the Theme.of(context).textTheme // to
"displayLarge" or "displaySmall".
style: Theme.of(context).textTheme.bodyMedium!.copyWith(
color: Theme.of(context).colorScheme.onPrimary,
),
),
),
),
floatingActionButton: Theme( data:
Theme.of(context).copyWith(
// TRY THIS: Change the seedColor to "Colors.red" or
// "Colors.blue".
colorScheme: ColorScheme.fromSeed( seedColor:
Colors.pink,
brightness: Brightness.dark,
),
),
child: FloatingActionButton( onPressed: ()
{}, child: const Icon(Icons.add),
),
),
);
}
}
Output:
Week 4
EXPERIMENT NO: 7.
import 'package:flutter/material.dart';
void main()
{ runApp(MyApp()); }
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text('Form Example'),
),
body: Padding( padding:
EdgeInsets.all(16.0), child:
Form( key: _formKey, child:
Column(
crossAxisAlignment:
CrossAxisAlignment.stretch, children: <Widget>[
TextFormField(
controller: _nameController, decoration:
InputDecoration( labelText: 'Name',
border: OutlineInputBorder(),
),
validator: (value) { if (value == null
|| value.isEmpty) {
return 'Please enter your name';
} return
null;
},
),
SizedBox(height: 16),
TextFormField( controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration( labelText:
'Email',
border: OutlineInputBorder(),
),
validator: (value) { if (value == null ||
value.isEmpty) { return 'Please enter your
email';
} else if (!RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$')
.hasMatch(value)) {
return 'Please enter a valid email address';
} return
null;
},
),
SizedBox(height: 16),
TextFormField( controller:
_passwordController, obscureText: true,
decoration: InputDecoration( labelText:
'Password',
border: OutlineInputBorder(),
),
validator: (value) { if (value == null
|| value.isEmpty) { return 'Please enter your
password'; } else if (value.length < 6) {
return 'Password must be at least 6 characters long';
} return
null;
},
),
SizedBox(height: 16), ElevatedButton(
onPressed: () { if (_formKey.currentState!.validate())
{ // Form is valid, process the
data print('Name: ${_nameController.text}');
print('Email: ${_emailController.text}');
print('Password: ${_passwordController.text}');
}
},
child: Text('Submit'),
),
],
),
),
),
);
}
}
Output:
7 b) Implement form validation and error handling.
Ans)
import 'package:flutter/material.dart';
void main() { runApp(MyApp());
}
Output:
EXPERIMENT NO: 8.
Ans)
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text('Animation Example'),
),
body: Center( child:
FadeTransition( opacity: _opacityAnimation,
child: Container( width:
200, height: 200, color:
Colors.blue, child: Center( child:
Text( 'Animated Widget',
style:
TextStyle( color: Colors.white,
fontSize: 20,
),
),
),
),
),
),
);
}
Output:
_animationController.forward(); }
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text('Fade Animation Example'),
),
body: Center( child: FadeTransition(
opacity: _opacityAnimation, child:
Container( width: 200, height:
200, color: Colors.blue, child:
Center( child: Text( 'Fade
Animation', style:
TextStyle( color: Colors.white,
fontSize: 20,
),
),
),
),
),
),
); }
Output:
Fade Animation
Slide Animation:
import 'package:flutter/material.dart';
void main() { runApp(MyApp());
}
@override
void initState() { super.initState();
_animationController.forward();
}
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text('Slide Animation Example'),
),
body: SlideTransition( position:
_slideAnimation, child:
Container( width: 200, height: 200,
color: Colors.blue,
child:
Center( child: Text( 'Slide
Animation', style: TextStyle(
color: Colors.white,
fontSize: 20,
),
),
),
),
),
);
}
@override void dispose()
{ _animationController.dispose();
super.dispose();
}
}
Output:
Slide Animation
Scale Animation:
_animationController.forward();
}
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text('Scale Animation Example'),
),
body: ScaleTransition( scale:
_scaleAnimation, child: Container(
width: 200, height: 200, color:
Colors.blue,
child:
Center( child: Text( 'Scale
Animation', style: TextStyle(
color: Colors.white, fontSize: 20,
),
),
),
),
),
); }
Output:
Week 5
EXPERIMENT NO: 9.
Output:
9 b) Display the fetched data in a meaningful way in the UI.
Ans)
import 'package:flutter/material.dart'; import
'package:http/http.dart' as http; import 'dart:convert';
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
List<Post> posts = data.map((post) => Post.fromJson(post)).toList(); return posts;
} else {
throw Exception('Failed to load posts');
}
}
@override
Widget build(BuildContext context)
{ return Scaffold( appBar: AppBar(
title: Text('API Fetch Example'),
),
body: FutureBuilder<List<Post>>( future: _posts, builder: (context,
snapshot) { if (snapshot.connectionState == ConnectionState.waiting)
{ return Center(child: CircularProgressIndicator());
} else if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
} else {
return PostList(posts: snapshot.data!);
}
},
),
);
}
}
PostList({required this.posts});
@override
Widget build(BuildContext context) { return
ListView.builder( itemCount: posts.length,
itemBuilder: (context, index) {
return PostItem(post: posts[index]);
},
);
}
}
PostItem({required this.post});
@override
Widget build(BuildContext context) { return Card(
margin: EdgeInsets.all(10),
elevation: 3, child:
Padding( padding: EdgeInsets.all(15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start, children:
[ Text( post.title, style:
TextStyle( fontSize: 18,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 10),
Text( post.body,
style: TextStyle(fontSize: 16),
),
],
),
),
);
}
}
Ans) Unit tests are handy for verifying the behavior of a single function, method, or class. The test
package provides the core framework for writing unit tests, and the flutter_test package provides
additional utilities for testing widgets.
This recipe demonstrates the core features provided by the test package using the following steps:
To add the test package as a dev dependency, run flutter pub add:
content_copy
counter_app/
lib/ counter.dart
test/
counter_test.dart 3. Create a class
to test
Next, you need a “unit” to test. Remember: “unit” is another name for a function, method, or class. For
this example, create a Counter class inside the lib/counter.dart file. It is responsible for incrementing and
decrementing a value starting at 0.
content_copy
// Import the test package and Counter class import
'package:counter_app/counter.dart'; import
'package:test/test.dart';
void main() {
test('Counter value should be incremented', () { final counter
= Counter(); counter.increment();
expect(counter.value, 1);
});
}
5. Combine multiple tests in a group
If you want to run a series of related tests, use the flutter_test package group function to categorize the
tests. Once put into a group, you can call flutter test on all tests in that group with one command.
content_copy
import 'package:counter_app/counter.dart'; import
'package:test/test.dart';
void main() {
group('Test start, increment, decrement', ()
{ test('value should start at 0', ()
{ expect(Counter().value, 0);
});
expect(counter.value, 1);
});
expect(counter.value, -1);
});
});
}
6. Run the tests
Now that you have a Counter class with tests in place, you can run the tests.
IntelliJ
content_copy
flutter test test/counter_test.dart
To run all tests you put into one group, run the following command from the root of the project:
To learn more about unit tests, you can execute this command:
10.b) Use Flutter's debugging tools to identify and fix issues.
Ans) Flutter provides a set of debugging tools that can help you identify and fix issues in your app. Here's
a step-by-step guide on how to use these tools:
1. Flutter DevTools:
Run your app with the flutter run command.
Open DevTools by running the following command in your terminal: bash
Open your app in a Chrome browser and connect it to DevTools by clicking on the "Open DevTools"
button in the terminal or by navigating to http://127.0.0.1:9100/. DevTools provides tabs like Inspector,
Timeline, Memory, and more.
2. Flutter Inspector:
Use the Flutter Inspector in your integrated development environment (IDE) like Android Studio or
Visual Studio Code.
Toggle the Inspector in Android Studio with the shortcut Alt + Shift + D (Windows/Linux) or Option +
Shift + D (Mac).
Inspect the widget tree, modify widget properties, and observe widget relationships.
3. Hot Reload:
Leverage Hot Reload to see the immediate effect of code changes without restarting the entire app.
Press R in the terminal or use the "Hot Reload" button in your IDE.
5. Logging:
Utilize the print function to log messages to the console.
print('Debugging message');
View logs in the terminal or the "Logs" tab in DevTools.
6. Debug Paint:
Enable debug paint to visualize the layout and rendering of widgets. Use the
debugPaintSizeEnabled and debugPaintBaselinesEnabled flags.
void main() {
debugPaintSizeEnabled = true; // Shows bounding boxes of widgets
runApp(MyApp()); }
7. Memory Profiling:
Use the "Memory" tab in DevTools to analyze memory usage and identify potential memory leaks.
Monitor object allocations and deallocations.