0% found this document useful (0 votes)
11 views62 pages

Flutter and Dart Experiment Guide

The document outlines a series of experiments for students to implement using Flutter and Dart, covering installation, widget exploration, responsive UI design, navigation, state management, custom widgets, form handling, animations, API data fetching, and unit testing. Each experiment includes specific tasks and example code snippets to facilitate learning. The document serves as a comprehensive guide for practical hands-on experience with Flutter and Dart development.

Uploaded by

nagasair.12345
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)
11 views62 pages

Flutter and Dart Experiment Guide

The document outlines a series of experiments for students to implement using Flutter and Dart, covering installation, widget exploration, responsive UI design, navigation, state management, custom widgets, form handling, animations, API data fetching, and unit testing. Each experiment includes specific tasks and example code snippets to facilitate learning. The document serves as a comprehensive guide for practical hands-on experience with Flutter and Dart development.

Uploaded by

nagasair.12345
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

List of Experiments: Students need to implement the following experiments

1. a) Install Flutter and Dart SDK.


b) Write a simple Dart program to understand the language basics.
2. a) Explore various Flutter widgets (Text, Image, Container, etc.).
b) Implement different layout structures using Row, Column, and Stack widgets.
3. a) Design a responsive UI that adapts to different screen sizes.
b) Implement media queries and breakpoints for responsiveness.
4. a) Set up navigation between different screens using Navigator.
b) Implement navigation with named routes.
5. a) Learn about stateful and stateless widgets.
b) Implement state management using set State and Provider.
6. a) Create custom widgets for specific UI elements.
b) Apply styling using themes and custom styles.
7. a) Design a form with various input fields.
b) Implement form validation and error handling.
8. a) Add animations to UI elements using Flutter's animation framework.
b) Experiment with different types of animations (fade, slide, etc.).
9. a) Fetch data from a REST API.
b) Display the fetched data in a meaningful way in the UI.
10. a) Write unit tests for UI components.
b) Use Flutter's debugging tools to identify and fix issues.

Kumar Bhargav 1
1. a) Install Flutter and Dart SDK.
Ans)
FLUTTER :

Step 1 : Download Flutter SDK


Go to: [Link]
Download ZIP file for Windows

Step 2 : Extract ZIP File


Extract to: C:\src\flutter (recommended path, avoid spaces)

Step 3 : Set Path Variable


Add C:\src\flutter\bin to Environment Variables → System PATH

Step 4 : Verify Installation


Open CMD and run:

flutter doctor

This checks Flutter, Dart, Android Studio, etc.

Step 5 : Install Android Studio (if not done already)


For emulators and Flutter development tool

DART :

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:
[Link]

Kumar Bhargav 2
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:

Kumar Bhargav 3
Step 3: Running Dart. Now open bin folder and type “cmd” as given below:

Kumar Bhargav 4
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:

Kumar Bhargav 5
Now we are done to use Dart from anywhere in the file system.

Kumar Bhargav 6
Step 5: Run Dart Using cmd

1. b) Write a simple Dart program to understand the language basics.


Ans)

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;

Kumar Bhargav 7
int diff = num1 - num2;
int mul = num1 * num2;
double div = num1 / num2; // It is double because it outputs number with
decimal.

// displaying the output


print("The sum is $sum");
print("The diff is $diff");
print("The mul is $mul");
print("The div is $div");
}

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 = [Link]([Link]()!);
print("The entered number is ${number}");
}
Output:
Enter number:
50
The entered number is 50

2. a) Explore various Flutter widgets (Text, Image, Container, etc.).

Text Widget :
import 'package:flutter/[Link]';

void main() => runApp(const GeeksforGeeks());

class GeeksforGeeks extends StatelessWidget {


const GeeksforGeeks({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
backgroundColor: [Link],
title: const Text("Welcome Screen"),
),
body: const Center(
Kumar Bhargav 8
child: Text(
"Hello world!!",
style: TextStyle(fontSize: 24, color: [Link]),
),
),
),
);
}
}

Output :

Image Widget :
import 'package:flutter/[Link]';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {


const MyApp({Key? key}) : super(key: key);

// Root widget of your application


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Insert Image Demo'),
),
body: Center(
child: Column(
Kumar Bhargav 9
mainAxisAlignment: [Link],
children: <Widget>[
// First Image with opacity
Opacity(
opacity: 0.5,
child: [Link](
'assets/images/[Link]',
height: 200,
scale: 2.5,
// color: [Link](255, 15, 147, 59), // Optional color filter
),
),

const SizedBox(height: 20), // spacing between images

// Second Image without opacity


[Link](
'assets/images/[Link]',
height: 400,
width: 400,
fit: [Link],
),
],
),
),
),
);
}
}

Output:

Kumar Bhargav 10
Container Widget :

import 'package:flutter/[Link]';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {


const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container Example"),
),
body: Container(
height: 200,
width: [Link],
alignment: [Link],
margin: const [Link](20),
padding: const [Link](30),
decoration: BoxDecoration(
border: [Link](
color: [Link],
width: 3,
),
// Optional: Add color or rounded corners
// color: [Link],
// borderRadius: [Link](10),
),
child: const Text(
"Hello! I am inside a container!",
style: TextStyle(fontSize: 20),
),
),
),
);
}
}

OUTPUT:

Kumar Bhargav 11
2 .b) Implement different layout structures using Row, Column, and Stack widgets

ROW WIDGET :
import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


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

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Row Example"),
Kumar Bhargav 12
),
body: Row(
mainAxisAlignment: [Link],
children: <Widget>[
Container(
margin: [Link](12.0),
padding: [Link](8.0),
decoration: BoxDecoration(
borderRadius: [Link](8),
color: [Link],
),
child: Text(
"[Link]",
style: TextStyle(color: [Link], fontSize: 25),
),
),
Container(
margin: [Link](15.0),
padding: [Link](8.0),
decoration: BoxDecoration(
borderRadius: [Link](8),
color: [Link],
),
child: Text(
"[Link]", // <-- You can change this label as needed
style: TextStyle(color: [Link], fontSize: 25),
),
),
Container(
margin: [Link](12.0),
padding: [Link](8.0),
decoration: BoxDecoration(
borderRadius: [Link](8),
color: [Link],
),
child: Text(
"Flutter",
style: TextStyle(color: [Link], fontSize: 25),
),
),
],
),
);
}
}

OUTPUT:

Kumar Bhargav 13
Column Widget:
import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


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

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Column Example"),
),
Kumar Bhargav 14
body: Column(
mainAxisAlignment: [Link],
children: <Widget>[
Container(
margin: [Link](20.0),
padding: [Link](12.0),
decoration: BoxDecoration(
borderRadius: [Link](8),
color: [Link],
),
child: Text(
"MySQL",
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
Container(
margin: [Link](20.0),
padding: [Link](12.0),
decoration: BoxDecoration(
borderRadius: [Link](8),
color: [Link],
),
child: Text(
"[Link]",
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
Container(
margin: [Link](20.0),
padding: [Link](12.0),
decoration: BoxDecoration(
borderRadius: [Link](8),
color: [Link],
),
child: Text(
"Flutter",
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
],
),
);
Kumar Bhargav 15
}
}

OUTPUT :

Stack Widget:
import 'package:flutter/[Link]';

void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: [Link][400],
),
body: Center(
child: SizedBox(
width: 300,
height: 300,
child: Stack(
children: <Widget>[
Container(
width: 300,
height: 300,
color: [Link],
),
Container(
width: 250,
height: 250,
Kumar Bhargav 16
color: [Link],
),
Container(
width: 200,
height: 200,
color: [Link],
),
],
),
),
),
),
),
);
}

OUTPUT :

3. a) Design a responsive UI that adapts to different screen sizes.

import 'package:flutter/[Link]';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {


const MyApp({[Link]});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Responsive UI',
debugShowCheckedModeBanner: false,
home: const ResponsiveHomePage(),
);
Kumar Bhargav 17
}
}

class ResponsiveHomePage extends StatelessWidget {


const ResponsiveHomePage({[Link]});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Responsive UI Example'),
backgroundColor: [Link],
),
body: LayoutBuilder(
builder: (context, constraints) {
if ([Link] < 600) {
// Small screen (mobile)
return _buildColumnLayout();
} else {
// Large screen (tablet or desktop)
return _buildRowLayout();
}
},
),
);
}

// Vertical layout for small screens


Widget _buildColumnLayout() {
return SingleChildScrollView(
child: Column(
children: [
_buildBox("Section 1", [Link]),
_buildBox("Section 2", [Link]),
],
),
);
}

// Horizontal layout for wide screens


Widget _buildRowLayout() {
return Row(
children: [
Expanded(child: _buildBox("Section 1", [Link])),
Expanded(child: _buildBox("Section 2", [Link])),
],
);
}

Widget _buildBox(String title, Color color) {


return Container(
Kumar Bhargav 18
margin: const [Link](16),
padding: const [Link](24),
decoration: BoxDecoration(
color: [Link](0.8),
borderRadius: [Link](12),
),
child: Center(
child: Text(
title,
style: const TextStyle(fontSize: 24, color: [Link]),
),
),
);
}
}

Output :

3 .b) Implement media queries and breakpoints for responsiveness.

import 'package:flutter/[Link]';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Responsive Demo',
home: ResponsiveHome(),
);

Kumar Bhargav 19
}
}

class ResponsiveHome extends StatelessWidget {


@override
Widget build(BuildContext context) {
// Get screen width using MediaQuery
double screenWidth = [Link](context).[Link];

Widget content;

if (screenWidth < 600) {


// Mobile
content = MobileView();
} else if (screenWidth < 1200) {
// Tablet
content = TabletView();
} else {
// Desktop
content = DesktopView();
}

return Scaffold(
appBar: AppBar(title: Text("Responsive Layout")),
body: content,
);
}
}

class MobileView extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Center(child: Text(" Mobile View", style: TextStyle(fontSize: 24)));
}
}

class TabletView extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Center(child: Text(" Tablet View", style: TextStyle(fontSize: 30)));
}
}

class DesktopView extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Center(child: Text(" Desktop View", style: TextStyle(fontSize: 36)));
}
}

Kumar Bhargav 20
Output:

4 .a) Set up navigation between different screens using Navigator.

import 'package:flutter/[Link]';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {


const MyApp({[Link]});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Screen Navigation Example',
debugShowCheckedModeBanner: false,
home: const NavigationScreen(),
);
}
}

class NavigationScreen extends StatefulWidget {


const NavigationScreen({[Link]});

@override
State<NavigationScreen> createState() => _NavigationScreenState();
}

class _NavigationScreenState extends State<NavigationScreen> {


String currentScreen = 'home';

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
Kumar Bhargav 21
title: const Text('Screen Navigation Example'),
backgroundColor: Colors.black87,
),
body: Center(
child: currentScreen == 'home' ? _buildHomeScreen() : _buildAboutScreen(),
),
bottomNavigationBar: Container(
color: Colors.black87,
padding: const [Link](12),
child: const Center(
child: Text(
'© 2024 Your Company Name',
style: TextStyle(color: [Link]),
),
),
),
);
}

Widget _buildHomeScreen() {
return Column(
mainAxisAlignment: [Link],
children: [
const Text('Welcome to the Home Screen.', style: TextStyle(fontSize: 20)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => setState(() => currentScreen = 'about'),
child: const Text('Go to About'),
),
],
);
}

Widget _buildAboutScreen() {
return Column(
mainAxisAlignment: [Link],
children: [
const Text('This is the About Screen.', style: TextStyle(fontSize: 20)),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () => setState(() => currentScreen = 'home'),
child: const Text('Go to Home'),
),
],
);
}
}

Output :

Kumar Bhargav 22
4 .b) Implement navigation with named routes.

import 'package:flutter/[Link]'; void main() {


runApp(MyApp());
}

class MyApp extends StatelessWidget { @override


Widget build(BuildContext context) { return MaterialApp(
title: 'Named Routes Navigation Example', initialRoute: '/',
routes: {
'/': (context) => HomeScreen(), '/about': (context) => AboutScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget { @override
Widget build(BuildContext context) { return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center( child: Column(
mainAxisAlignment: [Link], children: <Widget>[
Text(
'Welcome to the Home Screen.',
),
SizedBox(height: 20), ElevatedButton( onPressed: () {
[Link](context, '/about');
},
child: Text('Go to About'),
),

Kumar Bhargav 23
],
),
),
);
}
}

class AboutScreen extends StatelessWidget { @override


Widget build(BuildContext context) { return Scaffold(
appBar: AppBar(
title: Text('About Screen'),
),
body: Center( child: Column(
mainAxisAlignment: [Link], children: <Widget>[
Text(
'This is the About Screen.',
),
SizedBox(height: 20), ElevatedButton( onPressed: () {
[Link](context);
},
child: Text('Go back to Home'),
),
],
),
),
);
}
}

Output :

Kumar Bhargav 24
5 .a) Learn about stateful and stateless widgets.

import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget


{ @override
Widget build(BuildContext context)
{ return MaterialApp(
title: 'Stateful and Stateless Example',
theme: ThemeData(

primarySwatch: [Link],
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget


{ @override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>


{ int counter = 0;

void incrementCounter()
{ setState(() {
counter++;
});
}

@override
Widget build(BuildContext context)
{ return Scaffold(
appBar: AppBar(
title: Text('Stateful and Stateless Example'),
),
body: Column(
mainAxisAlignment: [Link],
children: <Widget>[
CounterDisplay(counter),
SizedBox(height: 20),
CounterButton(incrementCounter),
],
Kumar Bhargav 25
),
);
}
}

class CounterDisplay extends StatelessWidget


{ final int count;

CounterDisplay([Link]);

@override
Widget build(BuildContext context) {

return Text(
'Counter Value: $count',
style: TextStyle(fontSize: 20),
);
}
}

class CounterButton extends StatelessWidget


{ final VoidCallback onPressed;

CounterButton([Link]);

@override
Widget build(BuildContext context)
{ return ElevatedButton(
onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}

Output :

Kumar Bhargav 26
5 .b) Implement state management using set State and Provider.

import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget {


const MyApp({[Link]});

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

class HomePage extends StatefulWidget {


const HomePage({[Link]});

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {


int counterA = 0;
int counterB = 0;

void incrementA() {
setState(() {
counterA++;
});
}

void incrementB() {
setState(() {
counterB++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('setState Example')),
body: Padding(
padding: const [Link](30),
child: Column(
mainAxisAlignment: [Link],
children: [
Kumar Bhargav 27
const Text("Counter A", style: TextStyle(fontSize: 18)),
Text("Value: $counterA", style: const TextStyle(fontSize: 24)),
ElevatedButton(
onPressed: incrementA,
child: const Text("Increment A"),
),
const SizedBox(height: 40),
const Text("Counter B", style: TextStyle(fontSize: 18)),
Text("Value: $counterB", style: const TextStyle(fontSize: 24)),
ElevatedButton(
onPressed: incrementB,
child: const Text("Increment B"),
),
],
),
),
);
}
}

Output :

Kumar Bhargav 28
6 .a) Create custom widgets for specific UI elements.

import 'package:flutter/[Link]';

class CustomButton extends StatelessWidget {


final String text;
final VoidCallback onPressed;
final Color buttonColor;
final Color textColor;

const CustomButton({
[Link],
required [Link],
required [Link],
[Link] = [Link],
[Link] = [Link],
});

@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
style: ButtonStyle(
backgroundColor: [Link]<Color>(buttonColor),
foregroundColor: [Link]<Color>(textColor),
),
child: Text(text),
);
}
}

class CustomAlertDialog extends StatelessWidget {


final String title;
final String message;
final String positiveButtonText;
final String negativeButtonText;
final VoidCallback onPositivePressed;
final VoidCallback onNegativePressed;

const CustomAlertDialog({
[Link],
required [Link],
required [Link],
required [Link],
required [Link],
required [Link],
required [Link],
});

@override
Widget build(BuildContext context) {
Kumar Bhargav 29
return AlertDialog(
title: Text(title),
content: Text(message),
actions: <Widget>[
CustomButton(
text: negativeButtonText,
onPressed: onNegativePressed,
),
CustomButton(
text: positiveButtonText,
onPressed: onPositivePressed,
),
],
);
}
}

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

class MyApp extends StatelessWidget {


const MyApp({[Link]});

void showCustomDialog(BuildContext context) {


showDialog(
context: context,
builder: (context) => CustomAlertDialog(
title: 'Confirmation',
message: 'Are you sure you want to proceed?',
positiveButtonText: 'Yes',
negativeButtonText: 'No',
onPositivePressed: () {
[Link](context).pop();
print('Confirmed!');
},
onNegativePressed: () {
[Link](context).pop();
print('Cancelled!');
},
),
);
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Custom Button Example'),
),
Kumar Bhargav 30
body: Center(
child: CustomButton(
text: 'Click Me',
onPressed: () {
showCustomDialog(context);
},
),
),
),
);
}
}

Output:

6 .b) Apply styling using themes and custom styles.

import 'package:flutter/[Link]';

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

/// Entry point of the app with global theme.


class MyApp extends StatelessWidget {
const MyApp({[Link]});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Custom Styled App',
Kumar Bhargav 31
theme: ThemeData(
useMaterial3: true,
colorScheme: [Link](
seedColor: [Link],
brightness: [Link],
),
textTheme: const TextTheme(
titleLarge: TextStyle(
fontSize: 22,
fontWeight: [Link],
color: Colors.black87,
),
bodyMedium: TextStyle(
fontSize: 16,
color: Colors.black87,
),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: [Link](
backgroundColor: [Link],
foregroundColor: [Link],
padding: const [Link](horizontal: 24, vertical: 12),
textStyle: const TextStyle(fontSize: 16),
),
),
),
home: const HomePage(),
);
}
}

/// Custom reusable button widget (uses theme style).


class CustomButton extends StatelessWidget {
final String text;
final VoidCallback onPressed;

const CustomButton({
[Link],
required [Link],
required [Link],
});

@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(text),
);
}
}

Kumar Bhargav 32
/// Custom alert dialog using themed text and buttons.
class CustomAlertDialog extends StatelessWidget {
final String title;
final String message;
final String positiveButtonText;
final String negativeButtonText;
final VoidCallback onPositivePressed;
final VoidCallback onNegativePressed;

const CustomAlertDialog({
[Link],
required [Link],
required [Link],
required [Link],
required [Link],
required [Link],
required [Link],
});

@override
Widget build(BuildContext context) {
final theme = [Link](context);
return AlertDialog(
title: Text(title, style: [Link]),
content: Text(message, style: [Link]),
actions: [
CustomButton(text: negativeButtonText, onPressed: onNegativePressed),
CustomButton(text: positiveButtonText, onPressed: onPositivePressed),
],
);
}
}

/// Main home screen


class HomePage extends StatelessWidget {
const HomePage({[Link]});

void showCustomDialog(BuildContext context) {


showDialog(
context: context,
builder: (context) => CustomAlertDialog(
title: 'Confirm',
message: 'Are you sure?',
positiveButtonText: 'Yes',
negativeButtonText: 'No',
onPositivePressed: () {
[Link](context);
debugPrint('Confirmed!');
},
onNegativePressed: () {
[Link](context);
Kumar Bhargav 33
debugPrint('Cancelled!');
},
),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Styled Flutter UI',
style: [Link](context).[Link]),
backgroundColor: [Link](context).[Link],
),
body: Center(
child: CustomButton(
text: 'Show Dialog',
onPressed: () => showCustomDialog(context),
),
),
);
}
}

Output :

Kumar Bhargav 34
7 .a) Design a 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: MyForm(),
);
}
}

class MyForm extends StatefulWidget


{ @override
_MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm>


{ final _formKey = GlobalKey<FormState>();
TextEditingController _nameController = TextEditingController();
TextEditingController _emailController = TextEditingController();
TextEditingController _passwordController = TextEditingController();

@override
Widget build(BuildContext context)
{ return Scaffold(
appBar: AppBar(
title: Text('Form Example'),
),
body: Padding(
padding: [Link](16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
controller: _nameController,
decoration:
InputDecoration( labelText:
'Name',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link])
{ return 'Please enter your name';
}
Kumar Bhargav 35
return null;
},
),
SizedBox(height: 16),
TextFormField(
controller: _emailController,
keyboardType: [Link],
decoration: InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link])
{ 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 || [Link])
{ return 'Please enter your password';
} else if ([Link] < 6) {
return 'Password must be at least 6 characters long';
}
return null;
},
),
SizedBox(height: 16),
ElevatedButton( onPr
essed: () {
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'),
),
],
),
),
),
);
}
}

Kumar Bhargav 36
Output:

7 . b) Implement form validation and error handling.

import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget


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

class MyForm extends StatefulWidget


{ @override
_MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm>


{ final _formKey = GlobalKey<FormState>();
TextEditingController _nameController =
Kumar Bhargav 37
TextEditingController(); TextEditingController

_emailController = TextEditingController();

TextEditingController _passwordController =

TextEditingController();

@override
Widget build(BuildContext context)
{ return Scaffold(
appBar: AppBar(
title: Text('Form Validation Example'),
),
body: Padding(
padding: [Link](16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
controller: _nameController,
decoration:
InputDecoration( labelText:
'Name',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link])
{ return 'Please enter your name';
}
return null;
},
),
SizedBox(height: 16),
TextFormField(
controller: _emailController,
keyboardType: [Link],
decoration: InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link])
{ return 'Please enter your email';
} else if (!RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$')
.hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
},
Kumar Bhargav 38
),
SizedBox(height: 16),

TextFormField(
controller: _passwordController,
obscureText: true,
decoration:
InputDecoration( labelText:
'Password',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link])
{ return 'Please enter your
password';
} else if ([Link] < 6) {
return 'Password must be at least 6 characters long';
}
return null;
},
),
SizedBox(height: 16),
ElevatedButton( onPr
essed: () {
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:

Kumar Bhargav 39
8 .a) Add animations to UI elements using Flutter's animation framework.

import 'package:flutter/[Link]';

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

class MyApp extends StatelessWidget


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

class MyAnimatedWidget extends StatefulWidget


{ @override
_MyAnimatedWidgetState createState() => _MyAnimatedWidgetState();
}

class _MyAnimatedWidgetState extends State<MyAnimatedWidget>


Kumar Bhargav 40
with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _opacityAnimation;

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

// Create an AnimationController with a duration of 1 second


_animationController =
AnimationController( vsync: this,
duration: Duration(seconds: 1),
);

// Create a Tween to animate opacity from 0.0 to 1.0


_opacityAnimation = Tween<double>(begin: 0.0, end:
1.0).animate( CurvedAnimation(
parent: _animationController,
curve: [Link],
),
);

// Start the animation


_animationController.forward();
}

@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: [Link],
child:
Center( child:
Text(
'Animated Widget',
style:
TextStyle( color:
[Link],
fontSize: 20,
),
),

Kumar Bhargav 41
),
),
),
),
);
}

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

Output :

8 .b) Experiment with different types of animations (fade, slide, etc.).

Fade Animation :
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget
{ @override
Widget build(BuildContext context)
{ return MaterialApp(
title: 'Fade Animation Example',
theme:
ThemeData( primarySwatch:
[Link],
),
home: FadeAnimationWidget(),
);
}
Kumar Bhargav 42
}

class FadeAnimationWidget extends StatefulWidget


{ @override
_FadeAnimationWidgetState createState() => _FadeAnimationWidgetState();
}

class _FadeAnimationWidgetState extends State<FadeAnimationWidget>


with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _opacityAnimation;

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

_animationController =
AnimationController( vsync: this,
duration: Duration(seconds: 10),
);

_opacityAnimation = Tween<double>(begin: 0.0, end:


1.0).animate( CurvedAnimation(
parent: _animationController,
curve: [Link],
),
);

_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: [Link],
child:
Center( child:
Text(
'Fade Animation',
style:
Kumar Bhargav 43
TextStyle( color:
[Link],
fontSize: 20,
),
),
),
),
),
),
);
}

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

Output :

Slide Animation:
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget


{ @override
Widget build(BuildContext context)
Kumar Bhargav 44
{ return MaterialApp(
title: 'Slide Animation Example',
theme:
ThemeData( primarySwatch:
[Link],
),
home: SlideAnimationWidget(),
);
}
}

class SlideAnimationWidget extends StatefulWidget


{ @override
_SlideAnimationWidgetState createState() => _SlideAnimationWidgetState();
}

class _SlideAnimationWidgetState extends State<SlideAnimationWidget>


with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<Offset> _slideAnimation;

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

_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: [Link],
),
);

_animationController.forward();
}

@override
Widget build(BuildContext context)
{ return Scaffold(
appBar: AppBar(
title: Text('Slide Animation Example'),
),
body:
Kumar Bhargav 45
SlideTransition( position:
_slideAnimation, child:
Container(
width: 200,
height: 200,
color: [Link],
child:
Center( child:
Text(
'Slide Animation',
style:
TextStyle( color:
[Link],
fontSize: 20,
),
),
),
),
),
);
}
@override
void dispose() {
_animationController.dispose();
[Link]();
}
}

Output :

Kumar Bhargav 46
Scale Animation:
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget
{ @override
Widget build(BuildContext context)
{ return MaterialApp(
title: 'Scale Animation Example',
theme:
ThemeData( primarySwatch:
[Link],
),
home: ScaleAnimationWidget(),
);
}
}
class ScaleAnimationWidget extends StatefulWidget
{ @override
_ScaleAnimationWidgetState createState() => _ScaleAnimationWidgetState();
}

class _ScaleAnimationWidgetState extends State<ScaleAnimationWidget>


with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _scaleAnimation;

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

_animationController =
AnimationController( vsync: this,
duration: Duration(seconds: 2),
);

_scaleAnimation = Tween<double>(begin: 0.5, end:


1.0).animate( CurvedAnimation(
parent: _animationController,
curve: [Link],
),
);

_animationController.forward();
}

@override
Widget build(BuildContext context)
{ return Scaffold(
appBar: AppBar(
Kumar Bhargav 47
title: Text('Scale Animation Example'),
),
body:
ScaleTransition( scale:
_scaleAnimation, child:
Container( width: 200,
height: 200,
color: [Link],
child:
Center( child:
Text(
'Scale Animation',
style:
TextStyle( color:
[Link],
fontSize: 20,
),
),
),
),
),
);
}

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

Output :

Kumar Bhargav 48
9 .a) Fetch data from a REST API.

import 'dart:convert';
import 'dart:io';

import 'package:flutter/[Link]';

void main() {
runApp(MaterialApp(
home: SimpleApiWithoutHttpPackage(),
));
}

class SimpleApiWithoutHttpPackage extends StatefulWidget {


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

class _SimpleApiWithoutHttpPackageState
extends State<SimpleApiWithoutHttpPackage> {
List posts = [];

// Use Dart's built-in HttpClient to fetch data


Future<void> fetchData() async {
final client = HttpClient();
try {
final request = await client
.getUrl([Link]('[Link]
final response = await [Link]();

if ([Link] == 200) {
final responseBody = await [Link]([Link]).join();
final List data = [Link](responseBody);
setState(() {
posts = data;
});
} else {
print('Failed to load data. Status code: ${[Link]}');
}
} catch (e) {
print('Error: $e');
} finally {
[Link]();
}
}

@override
void initState() {
[Link]();
fetchData();
}
Kumar Bhargav 49
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('API Without Package')),
body: [Link]
? Center(child: CircularProgressIndicator())
: [Link](
itemCount: [Link],
itemBuilder: (context, index) {
return ListTile(
title: Text(posts[index]['title']),
subtitle: Text(posts[index]['body']),
);
},
),
);
}
}

Output :

9. b) Display the fetched data in a meaningful way in the UI.

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

void main() {
runApp(MaterialApp(
title: 'Meaningful API UI',
Kumar Bhargav 50
home: MeaningfulApiDisplay(),
debugShowCheckedModeBanner: false,
));
}

class MeaningfulApiDisplay extends StatefulWidget {


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

class _MeaningfulApiDisplayState extends State<MeaningfulApiDisplay> {


List posts = [];

Future<void> fetchData() async {


final client = HttpClient();
try {
final request = await [Link](
[Link]('[Link]
);
final response = await [Link]();

if ([Link] == 200) {
final responseBody = await [Link]([Link]).join();
final List data = [Link](responseBody);
setState(() {
posts = data;
});
} else {
print('Failed to fetch data: ${[Link]}');
}
} catch (e) {
print('Error: $e');
} finally {
[Link]();
}
}

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

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('API Data Display')),
body: [Link]
? const Center(child: CircularProgressIndicator())
: [Link](
padding: const [Link](10),
itemCount: [Link],
itemBuilder: (context, index) {
final post = posts[index];
return Card(
elevation: 4,
Kumar Bhargav 51
margin: const [Link](vertical: 8),
shape: RoundedRectangleBorder(
borderRadius: [Link](10),
),
child: ListTile(
leading: CircleAvatar(
backgroundColor: [Link],
child: Text(
post['id'].toString(),
style: const TextStyle(color: [Link]),
),
),
title: Text(
post['title'],
style: const TextStyle(
fontWeight: [Link],
),
),
subtitle: Text(post['body']),
trailing: const Icon(Icons.article_outlined),
),
);
},
),
);
}
}

Output :

Kumar Bhargav 52
10. a) Write unit tests for UI components.

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:

Add the test or flutter_test dependency.


Create a test file.
Create a class to test.
Write a test for our class.
Combine multiple tests in a group.
Run the tests.
For more information about the test package, see the test package documentation.

1. Add the test dependency


The test package provides the core functionality for writing tests in Dart. This is the
best approach when writing packages consumed by web, server, and Flutter apps.

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: [Link] and counter_test.dart.

The [Link] 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.

Kumar Bhargav 53
In general, test files should reside inside a test folder located at the root of your Flutter
application or package. Test files should always end with _test.dart, this is the
convention used by the test runner when searching for tests.

When you’re finished, the folder structure should look like this:

content_copy
counter_app/
lib/
[Link]
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/[Link]
file. It is responsible for incrementing and decrementing a value starting at 0.

content_copy
class Counter
{ int value = 0;

void increment() => value++;

void decrement() => value--;


}
Note: For simplicity, this tutorial does not follow the “Test Driven Development”
approach. If you’re more comfortable with that style of development, you can always
go that route.

4. Write a test for our class


Inside the counter_test.dart file, write the first unit test. Tests are defined using the
top-level test function, and you can check if the results are correct by using the top-
level expect function. Both of these functions come from the test package.

content_copy
// Import the test package and Counter class
import 'package:counter_app/[Link]';
import 'package:test/[Link]';

void main() {
test('Counter value should be incremented', ()
{ final counter = Counter();

[Link]();

Kumar Bhargav 54
expect([Link], 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/[Link]';
import 'package:test/[Link]';

void main() {
group('Test start, increment, decrement', ()
{ test('value should start at 0', ()
{ expect(Counter().value, 0);
});

test('value should be incremented', ()


{ final counter = Counter();

[Link]();

expect([Link], 1);
});

test('value should be decremented', ()


{ final counter = Counter();

[Link]();

expect([Link], -1);
});
});
}
6. Run the tests
Now that you have a Counter class with tests in place, you can run the tests.

Run tests using IntelliJ or VSCode


The Flutter plugins for IntelliJ and VSCode support running tests. This is often the
best option while writing tests because it provides the fastest feedback loop as well as
the ability to set breakpoints.

IntelliJ

Open the counter_test.dart file

Kumar Bhargav 55
Go to Run > Run ‘tests in counter_test.dart’. You can also press the appropriate
keyboard shortcut for your platform.
VSCode

Open the counter_test.dart file


Go to Run > Start Debugging. You can also press the appropriate keyboard shortcut
for your platform.
Run tests in a terminal
To run the all tests from the terminal, run the following command from the root of the
project:

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.

10 .b) Use Flutter's debugging tools to identify and fix issues.

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

flutter pub global activate devtools


flutter pub global run devtools

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 [Link]
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.

Kumar Bhargav 56
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.

4. Debugging with Breakpoints:


Set breakpoints in your code to pause execution and inspect variables. Use
the debugger in your IDE to step through code and identify issues.

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.

8. Performance Profiling (Timeline):


Analyze app performance using the "Timeline" tab in DevTools. Identify
UI jank, slow frames, and performance bottlenecks.

9. Flutter Driver Tests:


Write automated UI tests using Flutter Driver.
Simulate user interactions and validate the correctness of your UI.

Kumar Bhargav 57
Kumar Bhargav 58
Kumar Bhargav 59
Kumar Bhargav 60
Kumar Bhargav 61
Kumar Bhargav 62

You might also like