III I Ui Design Flutter Lab Manual r22
III I Ui Design Flutter Lab Manual r22
UI DESIGN-
FLUTTER LAB
MANUAL
Verified by HOD-CSE
TEXT BOOK:
1. Marco L. Napoli, Beginning Flutter: A Hands-on Guide to App Development.
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:
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.
void main(){
var firstName = "John";
var lastName = "Doe";
print("Full name is $firstName $lastName");
}
Output: Full name is John Doe
void main() {
int num1 = 10; //declaring number1
int num2 = 3; //declaring number2
// Calculation
int sum = num1 + num2;
Output:
The sum is 13
The diff is 7
The mul is 30
The div is 3.3333333333333335
import 'dart:io';
void main() {
print("Enter number:");
int? number = int.parse(stdin.readLineSync()!);
print("The entered number is ${number}");
}
Output:
Enter number:
50
The entered number is 50
Text Widget:
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context)
{ return MaterialApp(
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,
9
Downloaded by Roqia Tabassum
// 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:
import 'package:flutter/material.dart';
@override
Widget build(BuildContext context)
{ return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: double.infinity,
//color: Colors.purple,
alignment: Alignment.center,
margin: const EdgeInsets.all(20),
padding: const EdgeInsets.all(30),
decoration: BoxDecoration(
border: Border.all(color: Colors.black, width: 3),
),
child: const Text("Hello! i am inside a
container!", style: TextStyle(fontSize:
20)),
),
10
Output:
2b) Implement different layout structures using Row, Column, and Stack
import 'package:flutter/material.dart';
@override
return MaterialApp(
home: MyHomePage()
);
@override
11
@override
return Scaffold(
appBar: AppBar(
),
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children:<Widget>[
Container(
margin:
EdgeInsets.all(12.0),
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),
12
Downloaded by Roqia Tabassum
padding: EdgeInsets.all(8.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.green
),
child: Text("Flutter",style:
TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
Container(
margin: EdgeInsets.all(12.0),
padding: EdgeInsets.all(8.0),
decoration:BoxDecoration(
borderRadius:BorderRadius.circular(8),
color:Colors.green
),
child: Text("MySQL",style:
TextStyle(color:Colors.yellowAccent,fontSize:25),),
),
);
13
Column Widget:
import 'package:flutter/material.dart';
14
15
16
Output:
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>
17
<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:
18
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 {
19
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>
20
Output:
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;
}
21
section {
display: none;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
position: fixed;
bottom: 0;
width: 100%;
}
.active {
display: block;
}
</style>
</head>
<body>
<header class="jumbotron text-center">
<h1>Screen Navigation Example</h1>
</header>
<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>
22
<script>
function navigateTo(screenId) {
// Hide all sections
document.querySelectorAll('section').forEach(section => {
section.classList.remove('active');
});
Output:
23
Ans)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
24
25
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
26
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) {
27
CounterButton(this.onPressed);
@override
Widget build(BuildContext context)
{ return ElevatedButton(
onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}
Output:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterModel(),
child: MyApp(),
28
void incrementCounter() {
_counter++;
notifyListeners();
}
}
return Scaffold(
appBar: AppBar(
title: Text('State Management Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter Value: ${counterModel.counter}',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
29
Output:
Ans)
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget
{ final String text;
final Function onPressed;
final Color buttonColor;
final Color textColor;
CustomButton({
required this.text,
required this.onPressed,
this.buttonColor = Colors.blue,
this.textColor = Colors.white,
30
31
Output:
Ans)
32
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context)
{ const appName = 'Custom
Themes';
return MaterialApp(
title: appName,
theme: ThemeData(
useMaterial3: true,
33
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".
34
Output:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
35
@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',
36
Output:
37
handling. Ans)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
38
39
Output:
40
Ans)
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
41
@override
void initState() {
super.initState();
@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,
),
42
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
}
Output:
43
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 10),
);
_animationController.forward();
}
@override
Widget build(BuildContext context) {
44
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
}
Output:
Fade Animation
45
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
@override
46
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_slideAnimation =
Tween<Offset>( begin: Offset(-
1.0, 0.0),
end: Offset(0.0, 0.0),
).animate( CurvedA
nimation(
parent: _animationController,
curve: Curves.easeInOut,
),
);
_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,
),
),
),
),
),
);
}
47
Output:
Slide Animation
Scale Animation:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget
{ @override
Widget build(BuildContext context)
{ return MaterialApp(
title: 'Scale Animation Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ScaleAnimationWidget(),
);
}
}
48
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_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,
49
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
}
Output:
Ans)
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
50
@override
void initState() {
super.initState();
_posts = fetchPosts();
}
if (response.statusCode == 200) {
// If the server returns a 200 OK response,
// parse the JSON and return a list of posts.
List<dynamic> data = json.decode(response.body);
List<Post> posts = data.map((post) => Post.fromJson(post)).toList();
return posts;
} else {
// If the server did not return a 200 OK response,
// throw an exception.
throw Exception('Failed to load posts');
}
}
51
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({
required this.userId,
required this.id,
required this.title,
required this.body,
});
52
Output:
UI. Ans)
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
53
@override
void initState() {
super.initState();
_posts = fetchPosts();
}
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!);
}
},
54
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,
55
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({
required this.userId,
required this.id,
required this.title,
required this.body,
});
Output:
56
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
flutter pub add dev:test
2. Create a test file
In this example, create two files: counter.dart and counter_test.dart.
The counter.dart file contains a class that you want to test and resides in the lib folder.
The counter_test.dart file contains the tests themselves and lives inside the test folder.
57
When you’re finished, the folder structure should look like this:
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
class Counter {
int value = 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();
58
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);
});
counter.increment();
expect(counter.value, 1);
});
counter.decrement();
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
59
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:
content_copy
flutter test --plain-name "Test start, increment, decrement"
This example uses the group created in section 5.
To learn more about unit tests, you can execute this command:
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.
60
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.
61