0% found this document useful (0 votes)
24 views63 pages

Flutter Lab Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 63

UI DESIGN-FLUTTER

(R22 Regulation)

LAB MANUAL

III- B. Tech – I Semester

Department of Computer Sciences & Engineering


SREE CHAITANYA INSTITUTE OF TECHNOLOGICAL
SCIENCES
LMD COLONY, KARIMNAGAR-505527
(Approved by AICTE, Affiliated to JNTUH, Hyderabad)

B.Tech III-I UI DESIGN-FLUTTER,SCIT


INDEX
S. No. Experiments Page
No.

1
INDEX
a)Install Flutter and Dart SDK. 1

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

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

b)Implement different layout structures using Row, Column, and Stack

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

b)Implement media queries and break points for responsiveness

4 a) Setup navigation between different screens using Navigator. 14

b)Implement navigation with named routes

5 a) Learn about state-ful and stateless widgets. 19

b)Implement state management using set State and Provider.

6 a) Create custom widgets for specific UI elements. 24

b) Apply styling using themes and custom styles.

7 a) Design a form with various input fields. 28

b) Implement form validation and error handling.

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

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

9 a) Fetch data from a RESTAPI. 48

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

10 a) Write unit tests for UI components. 52

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

B.Tech III-I UI DESIGN-FLUTTER,SCIT


FLUTTER INTRODUCTION

In general, developing a mobile application is a complex and challenging task. There are many frameworks
available to develop a mobile application. Android provides a native framework based on Java language and
iOS provides a native framework based on Objective-C / Shift language.

However, to develop an application supporting both the OSs, we need to code in two different languages using
two different frameworks. To help overcome this complexity, there exists mobile frameworks supporting both
OS. These frameworks range from simple HTML based hybrid mobile application framework (which uses
HTML for User Interface and JavaScript for application logic) to complex language specific framework (which
do the heavy lifting of converting code to native code). Irrespective of their simplicity or complexity, these
frameworks always have many disadvantages, one of the main drawback being their slow performance.

In this scenario, Flutter – a simple and high performance framework based on Dart language, provides high
performance by rendering the UI directly in the operating system’s canvas rather than through native
framework. Flutter also offers many ready to use widgets (UI) to create a modern application. These widgets are
optimized for mobile environment and designing the application using widgets is as simple as designing HTML.

To be specific, Flutter application is itself a widget. Flutter widgets also supports animations and gestures. The
application logic is based on reactive programming. Widget may optionally have a state. By changing the state
of the widget, Flutter will automatically (reactive programming) compare the widget’s state (old and new) and
render the widget with only the necessary changes instead of re-rendering the whole widget.

B.Tech III-I UI DESIGN-FLUTTER,SCIT


FLUTTER INSTALLATION
Installation in Windows
Iinstall Flutter SDK

Step 1: Go to URL, https://flutter.dev/docs/get-started/install/windows and download the latest Flutter SDK.


As of April 2019, the version is 1.2.1 and the file is flutter_windows_v1.2.1-stable.zip.

Step 2: Unzip the zip archive in a folder, say C:\flutter\

Step 3: Update the system path to include flutter bin directory.

Step 4: Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met.
flutter doctor .

Step 5: Running the above command will analyze the system and show its report as shown below:

Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, v1.2.1, on Microsoft
Windows [Version 10.0.17134.706], locale en-US)

[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3) [√] Android Studio (version
3.2)

[√] VS Code, 64-bit edition (version 1.29.1) [!] Connected device ! No devices available ! Doctor found issues
in 1 category. The report says that all development tools are available but the device is not connected. We can
fix this by connecting an android device through USB or starting an android emulator.

Step 6: Install the latest Android SDK, if reported by flutter doctor

Step 7: Install the latest Android Studio, if reported by flutter doctor

Step 8: Start an android emulator or connect a real android device to the system.

Step 9: Install Flutter and Dart plugin for Android Studio. It provides startup template to create new Flutter
application, an option to run and debug Flutter application in the Android studio itself, etc.,

B.Tech III-I UI DESIGN-FLUTTER,SCIT


Open Android Studio

. Click File

 > Settings > Plugins.

Select the Flutter plugin and click Install.

 Click Yes when prompted to install the Dart plugin.

 Restart Android studio.

Installation in MacOS
To install Flutter on MacOS, you will have to follow the following steps:

Step 1: Go to URL, https://flutter.dev/docs/get-started/install/macos and download latest Flutter SDK. As of


April 2019, the version is 1.2.1 and the file is flutter_macos_v1.2.1- stable.zip.

Step 2: Unzip the zip archive in a folder, say /path/to/flutter

Step 3: Update the system path to include flutter bin directory (in ~/.bashrc file). > export
PATH="$PATH:/path/to/flutter/bin"

Step 4: Enable the updated path in the current session using below command and then verify it as well. source
~/.bashrc source $HOME/.bash_profile echo $PATH Flutter provides a tool, flutter doctor to check that all the
requirement of flutter development is met. It is similar to the Windows counterpart.

Step 5: Install latest XCode, if reported by flutter doctor

Step 6: Install latest Android SDK, if reported by flutter doctor

Step 7: Install latest Android Studio, if reported by flutter doctor

Step 8: Start an android emulator or connect a real android device to the system to develop android application.
Step 9: Open iOS simulator or connect a real iPhone device to the system to develop iOS application.

Step 10: Install Flutter and Dart plugin for Android Studio. It provides the startup template to create a new
Flutter application, option to run and debug Flutter application in the Android studio itself, etc.,

Open Android Studio.

 Click Preferences > Plugins.

Select the Flutter plugin and click Install

 Click Yes when prompted to install the Dart plugin.

 Restart Android studio.

B.Tech III-I UI DESIGN-FLUTTER,SCIT


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 URLis: 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 below

B.Tech III-I UI DESIGN-FLUTTER,SCIT


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

B.Tech III-I UI DESIGN-FLUTTER,SCIT


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 inenvironment
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 fromadvanced system
settings and add Path in System Variables as depicted in image:

B.Tech III-I UI DESIGN-FLUTTER,SCIT


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

B.Tech III-I UI DESIGN-FLUTTER,SCIT


Step 5: Run Dart Using cmd

B.Tech III-I UI DESIGN-FLUTTER,SCIT


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

void main() {

// Variables

String name = "John";

int age = 25;

double height = 5.9;

bool isStudent = true;

// Printing to the console

print("Hello, $name!");

print("Age: $age");

print("Height: $height feet");

print("Is a student? $isStudent");

// Function

int sum(int a, int b) {

return a + b;

// Calling a function

int result = sum(10, 5);

print("Sum: $result");

// Conditional statement

if (age >= 18) {

print("$name is an adult.");

1
} else {

print("$name is a minor.");

// Loop

for (int i = 1; i <= 5; i++) {

print("Count: $i");

// List

List<String> fruits = ["Apple", "Banana", "Orange"];

print("Fruits: $fruits");

// Map

Map<String, String> person = {

"name": "Alice",

"age": "30",

"job": "Engineer",

};

print("Person: $person");

OUTPUT :

Hello, John!

Age: 25

Height: 5.9 feet

2
Is a student? true

Sum: 15

John is an adult.

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

Fruits: [Apple, Banana, Orange]

Person: {name: Alice, age: 30, job: Engineer}

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

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Scaffold(

appBar: AppBar(

title: Text('Flutter Widgets Example'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

// Text Widget

Text(

'Hello, Flutter!',

style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),

),

// Image Widget

4
Image.network(

'https://example.com/flutter_logo.png',

width: 100,

height: 100,

),

// Container Widget

Container(

margin: EdgeInsets.all(20),

padding: EdgeInsets.all(10),

color: Colors.blue,

child: Text(

'Container Widget',

style: TextStyle(color: Colors.white),

),

),

],

),

),

),

);

OUTPUT:

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

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: ResponsiveUI(),

);

class ResponsiveUI extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Responsive UI Example'),

),

body: LayoutBuilder(

builder: (context, constraints) {

// Check the screen width

6
double screenWidth = constraints.maxWidth;

if (screenWidth > 600) {

// Large screen layout

return LargeScreenLayout();

} else {

// Small screen layout

return SmallScreenLayout();

},

),

);

class LargeScreenLayout extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Center(

child: Container(

width: 600,

padding: EdgeInsets.all(16),

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(

7
'Welcome to the Large Screen Layout!',

style: TextStyle(fontSize: 24),

),

SizedBox(height: 20),

FlutterLogo(size: 150),

],

),

),

);

class SmallScreenLayout extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Center(

child: Container(

padding: EdgeInsets.all(16),

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(

'Welcome to the Small Screen Layout!',

style: TextStyle(fontSize: 18),

),

SizedBox(height: 20),

8
FlutterLogo(size: 100),

],

),

),

);

OUTPUT:

3 b)Implement media queries and break points for responsiveness

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

9
return MaterialApp(

home: ResponsiveUI(),

);

class ResponsiveUI extends StatelessWidget {

@override

Widget build(BuildContext context) {

// Get the screen size

double screenWidth = MediaQuery.of(context).size.width;

// Determine breakpoints

bool isSmallScreen = screenWidth < 600;

bool isMediumScreen = screenWidth >= 600 && screenWidth < 900;

bool isLargeScreen = screenWidth >= 900;

// Return different layouts based on breakpoints

if (isSmallScreen) {

return SmallScreenLayout();

} else if (isMediumScreen) {

return MediumScreenLayout();

} else {

return LargeScreenLayout();

10
}

class SmallScreenLayout extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Small Screen Layout'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('Small Screen Content'),

SizedBox(height: 20),

FlutterLogo(size: 100),

],

),

),

);

class MediumScreenLayout extends StatelessWidget {

@override

Widget build(BuildContext context) {

11
return Scaffold(

appBar: AppBar(

title: Text('Medium Screen Layout'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('Medium Screen Content'),

SizedBox(height: 20),

FlutterLogo(size: 150),

],

),

),

);

class LargeScreenLayout extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Large Screen Layout'),

),

body: Center(

12
child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text('Large Screen Content'),

SizedBox(height: 20),

FlutterLogo(size: 200),

],

),

),

);

OUTPUT:

13
4a)Setup navigation between different screens using Navigator

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: HomeScreen(),

);

class HomeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Home Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

// Navigate to the second screen

14
Navigator.push(

context,

MaterialPageRoute(builder: (context) => SecondScreen()),

);

},

child: Text('Go to Second Screen'),

),

),

);

class SecondScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Second Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

// Navigate back to the home screen

Navigator.pop(context);

},

child: Text('Go back to Home Screen'),

),

),

15
);

OUTPUT:

4 b) Implement navigation with named routes.

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

// Define named routes

routes: {

'/': (context) => HomeScreen(),

'/second': (context) => SecondScreen(),

16
},

initialRoute: '/', // Set the initial route

);

class HomeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Home Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

// Navigate to the second screen using the named route

Navigator.pushNamed(context, '/second');

},

child: Text('Go to Second Screen'),

),

),

);

17
class SecondScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Second Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

// Navigate back to the home screen using the named route

Navigator.popAndPushNamed(context, '/');

},

child: Text('Go back to Home Screen'),

),

),

);

18
5 a) write a program state-ful and stateless widgets.
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Stateful and Stateless Widgets'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Stateless Widget
MyStatelessWidget(),

// Spacer for some space


SizedBox(height: 20),

// Stateful Widget
MyStatefulWidget(),
],
),
),
);
}
}

// Stateless Widget
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16),
color: Colors.blue,
child: Text(
'I am a Stateless Widget!',
style: TextStyle(fontSize: 20, color: Colors.white),
),
);
}
}

// Stateful Widget
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

19
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int counter = 0;

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

@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(16),
color: Colors.green,
child: Column(
children: [
Text(
'I am a Stateful Widget!',
style: TextStyle(fontSize: 20, color: Colors.white),
),
SizedBox(height: 10),
Text(
'Counter: $counter',
style: TextStyle(fontSize: 18, color: Colors.white),
),
SizedBox(height: 10),
ElevatedButton(
onPressed: incrementCounter,
child: Text('Increment Counter'),
),
],
),
);
}
}

OUTPUT:

20
5b) write a program state management using set State and Provider.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterProvider(),
child: MyApp(),
),
);
}

// -------------- State Management using setState --------------

class MyApp extends StatelessWidget {


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

class CounterAppWithSetState extends StatefulWidget {


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

class _CounterAppWithSetState extends State<CounterAppWithSetState> {


int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

void _decrementCounter() {
setState(() {
_counter--;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App with setState'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,

21
children: [
Text('Counter: $_counter'),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: _decrementCounter,
child: Text('Decrement'),
),
],
),
],
),
),
);
}
}

// -------------- State Management using Provider --------------

class CounterProvider with ChangeNotifier {


int _counter = 0;

int get counter => _counter;

void incrementCounter() {
_counter++;
notifyListeners();
}

void decrementCounter() {
_counter--;
notifyListeners();
}
}

class CounterAppWithProvider extends StatelessWidget {


@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App with Provider'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Consumer<CounterProvider>(
builder: (context, counterProvider, child) {
return Text('Counter: ${counterProvider.counter}');

22
},
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
Provider.of<CounterProvider>(context, listen: false)
.incrementCounter();
},
child: Text('Increment'),
),
SizedBox(width: 10),
ElevatedButton(
onPressed: () {
Provider.of<CounterProvider>(context, listen: false)
.decrementCounter();
},
child: Text('Decrement'),
),
],
),
],
),
),
);
}
}

OUTPUT:

23
.6 a) Create custom widgets for specific UI elements.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Custom Widgets Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CustomButton(
text: 'Press me!',
onPressed: () {
print('Button pressed!');
},
),
SizedBox(height: 20),
CustomCard(
title: 'Custom Card',
content: 'This is a custom card with some content.',
),
],
),
),
),
);
}
}

// Custom Button Widget


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

CustomButton({required this.text, required this.onPressed});

@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text(text),
style: ElevatedButton.styleFrom(
primary: Colors.blue,
textStyle: TextStyle(
fontSize: 18,

24
fontWeight: FontWeight.bold,
),
),
);
}
}

// Custom Card Widget


class CustomCard extends StatelessWidget {
final String title;
final String content;

CustomCard({required this.title, required this.content});

@override
Widget build(BuildContext context) {
return Container(
width: 300,
padding: EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 5,
offset: Offset(0, 3),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 10),
Text(
content,
style: TextStyle(fontSize: 16),
),
],
),
);
}
}
OUTPUT:

25
5 b) Apply styling using themes and custom styles
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

theme: ThemeData(

primaryColor: Colors.blue, // Set the primary color for the app

accentColor: Colors.orange, // Set the accent color

fontFamily: 'Roboto', // Set the default font family

textTheme: TextTheme(

headline1: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.black),

bodyText1: TextStyle(fontSize: 16, color: Colors.grey),

),

buttonTheme: ButtonThemeData(

buttonColor: Colors.blue, // Set the default button color

textTheme: ButtonTextTheme.primary, // Set the default button text theme

),

26
),

home: StyledApp(),

);

class StyledApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Styled App'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(

'Custom Styled Text',

style: Theme.of(context).textTheme.headline1,

),

SizedBox(height: 20),

ElevatedButton(

onPressed: () {

// Button click action

},

child: Text('Styled Button'),

),

27
],

),

),

);

OUTPUT :

7 a) Design a form with various input fields


import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Form Design Example',

theme: ThemeData(

primarySwatch: Colors.blue,

visualDensity: VisualDensity.adaptivePlatformDensity,

),

home: MyForm(),

28
);

class MyForm extends StatefulWidget {

@override

_MyFormState createState() => _MyFormState();

class _MyFormState extends State<MyForm> {

final _formKey = GlobalKey<FormState>();

String name = '';

String email = '';

String password = '';

String selectedCountry = 'USA';

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Form Design Example'),

),

body: Padding(

padding: EdgeInsets.all(16),

child: Form(

key: _formKey,

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,

29
children: [

TextFormField(

decoration: InputDecoration(

labelText: 'Name',

hintText: 'Enter your name',

),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your name';

return null;

},

onSaved: (value) {

name = value!;

},

),

SizedBox(height: 16),

TextFormField(

decoration: InputDecoration(

labelText: 'Email',

hintText: 'Enter your email',

),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your email';

// Add additional email validation if needed

return null;

30
},

onSaved: (value) {

email = value!;

},

),

SizedBox(height: 16),

TextFormField(

obscureText: true,

decoration: InputDecoration(

labelText: 'Password',

hintText: 'Enter your password',

),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your password';

// Add additional password validation if needed

return null;

},

onSaved: (value) {

password = value!;

},

),

SizedBox(height: 16),

DropdownButtonFormField<String>(

value: selectedCountry,

onChanged: (value) {

setState(() {

31
selectedCountry = value!;

});

},

items: ['USA', 'Canada', 'UK', 'Australia']

.map<DropdownMenuItem<String>>((String value) {

return DropdownMenuItem<String>(

value: value,

child: Text(value),

);

}).toList(),

decoration: InputDecoration(

labelText: 'Country',

),

),

SizedBox(height: 16),

ElevatedButton(

onPressed: () {

if (_formKey.currentState!.validate()) {

_formKey.currentState!.save();

// Process the form data, e.g., send it to a server

print('Name: $name, Email: $email, Password: $password, Country: $selectedCountry');

},

child: Text('Submit'),

),

],

),

),

32
),

);

OUTPUT:

7b)Implement form validation and error handling

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Form Validation Example',

33
theme: ThemeData(

primarySwatch: Colors.blue,

visualDensity: VisualDensity.adaptivePlatformDensity,

),

home: MyForm(),

);

class MyForm extends StatefulWidget {

@override

_MyFormState createState() => _MyFormState();

class _MyFormState extends State<MyForm> {

final _formKey = GlobalKey<FormState>();

String name = '';

String email = '';

String password = '';

String selectedCountry = 'USA';

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Form Validation Example'),

34
),

body: Padding(

padding: EdgeInsets.all(16),

child: Form(

key: _formKey,

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,

children: [

TextFormField(

decoration: InputDecoration(

labelText: 'Name',

hintText: 'Enter your name',

),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your name';

return null;

},

onSaved: (value) {

name = value!;

},

),

SizedBox(height: 16),

TextFormField(

decoration: InputDecoration(

35
labelText: 'Email',

hintText: 'Enter your email',

),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your email';

if (!RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$').hasMatch(value)) {

return 'Please enter a valid email address';

return null;

},

onSaved: (value) {

email = value!;

},

),

SizedBox(height: 16),

TextFormField(

obscureText: true,

decoration: InputDecoration(

labelText: 'Password',

hintText: 'Enter your password',

),

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your password';

36
}

// Add additional password validation if needed

return null;

},

onSaved: (value) {

password = value!;

},

),

SizedBox(height: 16),

DropdownButtonFormField<String>(

value: selectedCountry,

onChanged: (value) {

setState(() {

selectedCountry = value!;

});

},

items: ['USA', 'Canada', 'UK', 'Australia']

.map<DropdownMenuItem<String>>((String value) {

return DropdownMenuItem<String>(

value: value,

child: Text(value),

);

}).toList(),

decoration: InputDecoration(

labelText: 'Country',

),

37
),

SizedBox(height: 16),

ElevatedButton(

onPressed: () {

if (_formKey.currentState!.validate()) {

_formKey.currentState!.save();

// Process the form data, e.g., send it to a server

print('Name: $name, Email: $email, Password: $password, Country: $selectedCountry');

},

child: Text('Submit'),

),

],

),

),

),

);

OUTPUT:

38
8 a)Add animations to UI elements using Flutter's animation framework.

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Animation Example',

theme: ThemeData(

primarySwatch: Colors.blue,

visualDensity: VisualDensity.adaptivePlatformDensity,

),

home: MyAnimatedUI(),

);

class MyAnimatedUI extends StatefulWidget {

@override

_MyAnimatedUIState createState() => _MyAnimatedUIState();

class _MyAnimatedUIState extends State<MyAnimatedUI> {

39
double _containerWidth = 100.0;

double _containerHeight = 100.0;

Color _containerColor = Colors.blue;

void _animateContainer() {

setState(() {

_containerWidth = _containerWidth == 100.0 ? 200.0 : 100.0;

_containerHeight = _containerHeight == 100.0 ? 200.0 : 100.0;

_containerColor = _containerColor == Colors.blue ? Colors.red : Colors.blue;

});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Flutter Animation Example'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

AnimatedContainer(

duration: Duration(seconds: 1),

width: _containerWidth,

height: _containerHeight,

color: _containerColor,

child: Center(

40
child: Text(

'Animated Container',

style: TextStyle(

color: Colors.white,

fontWeight: FontWeight.bold,

),

),

),

),

SizedBox(height: 20),

ElevatedButton(

onPressed: _animateContainer,

child: Text('Animate Container'),

),

],

),

),

);

OUTPUT:

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

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Animation Types Example',

theme: ThemeData(

primarySwatch: Colors.blue,

visualDensity: VisualDensity.adaptivePlatformDensity,

),

home: MyAnimatedUI(),

);

class MyAnimatedUI extends StatefulWidget {

@override

_MyAnimatedUIState createState() => _MyAnimatedUIState();

42
class _MyAnimatedUIState extends State<MyAnimatedUI> {

bool _isFadeVisible = true;

bool _isSlideVisible = true;

bool _isScaleVisible = true;

void _toggleFade() {

setState(() {

_isFadeVisible = !_isFadeVisible;

});

void _toggleSlide() {

setState(() {

_isSlideVisible = !_isSlideVisible;

});

void _toggleScale() {

setState(() {

_isScaleVisible = !_isScaleVisible;

});

@override

Widget build(BuildContext context) {

return Scaffold(

43
appBar: AppBar(

title: Text('Flutter Animation Types Example'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

AnimatedOpacity(

opacity: _isFadeVisible ? 1.0 : 0.0,

duration: Duration(seconds: 1),

child: Container(

width: 100,

height: 100,

color: Colors.blue,

child: Center(

child: Text(

'Fade',

style: TextStyle(

color: Colors.white,

fontWeight: FontWeight.bold,

),

),

),

),

),

SizedBox(height: 20),

44
SlideTransition(

position: Tween<Offset>(

begin: Offset(_isSlideVisible ? -1.0 : 1.0, 0.0),

end: Offset.zero,

).animate(CurvedAnimation(

parent: ModalRoute.of(context)!.animation!,

curve: Curves.easeInOut,

)),

child: Container(

width: 100,

height: 100,

color: Colors.green,

child: Center(

child: Text(

'Slide',

style: TextStyle(

color: Colors.white,

fontWeight: FontWeight.bold,

),

),

),

),

),

SizedBox(height: 20),

ScaleTransition(

scale: Tween<double>(

45
begin: _isScaleVisible ? 0.0 : 1.0,

end: _isScaleVisible ? 1.0 : 0.0,

).animate(CurvedAnimation(

parent: ModalRoute.of(context)!.animation!,

curve: Curves.easeInOut,

)),

child: Container(

width: 100,

height: 100,

color: Colors.red,

child: Center(

child: Text(

'Scale',

style: TextStyle(

color: Colors.white,

fontWeight: FontWeight.bold,

),

),

),

),

),

SizedBox(height: 20),

Row(

mainAxisAlignment: MainAxisAlignment.spaceAround,

children: [

ElevatedButton(

46
onPressed: _toggleFade,

child: Text('Toggle Fade'),

),

ElevatedButton(

onPressed: _toggleSlide,

child: Text('Toggle Slide'),

),

ElevatedButton(

onPressed: _toggleScale,

child: Text('Toggle Scale'),

),

],

),

],

),

),

);

OUTPUT:

47
9 a) Fetch data from a RESTAPI

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter REST API Example',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {


List<Map<String, dynamic>> _posts = [];

@override
void initState() {
super.initState();
_fetchData();
}

Future<void> _fetchData() async {


final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

if (response.statusCode == 200) {
setState(() {
_posts = List<Map<String, dynamic>>.from(json.decode(response.body));
});
} else {
throw Exception('Failed to load data');
}
}

48
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter REST API Example'),
),
body: _posts.isEmpty
? Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: _posts.length,
itemBuilder: (context, index) {
final post = _posts[index];
return ListTile(
title: Text(post['title']),
subtitle: Text(post['body']),
);
},
),
);
}
}

OUTPUT:

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

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

49
}

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter REST API Example',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {


List<Map<String, dynamic>> _posts = [];

@override
void initState() {
super.initState();
_fetchData();
}

Future<void> _fetchData() async {


final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

if (response.statusCode == 200) {
setState(() {
_posts = List<Map<String, dynamic>>.from(json.decode(response.body));
});
} else {
throw Exception('Failed to load data');
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter REST API Example'),
),
body: _posts.isEmpty
? Center(
child: CircularProgressIndicator(),

50
)
: ListView.builder(
itemCount: _posts.length,
itemBuilder: (context, index) {
final post = _posts[index];
return Card(
margin: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: ListTile(
title: Text(
post['title'],
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
subtitle: Text(post['body']),
),
);
},
),
);
}
}

OUTPUT:

10 a)Write unit tests for UI components.

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
testWidgets('MyHomePage displays posts', (WidgetTester tester) async {
// Mocking the http response
final response = http.Response(jsonEncode([{'title': 'Post 1', 'body': 'Body 1'}]), 200);
http.Client client = MockClient((request) async => response);

51
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp(client: client));

// Wait for the data to be loaded.


await tester.pump();

// Verify that the list contains the post title.


expect(find.text('Post 1'), findsOneWidget);
});
}

class MockClient extends http.Client {


final Function(MockClientRequest) onRequest;

MockClient(this.onRequest);

@override
Future<http.Response> send(http.BaseRequest request) async {
onRequest(MockClientRequest(request));
return http.Response(jsonEncode({'error': 'Not Implemented'}), 500);
}
}

class MockClientRequest extends http.Request {


MockClientRequest(http.BaseRequest base) : super(base.method, base.url);

@override
final Map<String, String> headers = {};
}

OUTPUT:

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

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(

52
title: 'Debugging Example',
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {


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

class _MyHomePageState extends State<MyHomePage> {


int counter = 0;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Debugging Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Counter Value: $counterr', // Intentional typo in variable name
style: TextStyle(fontSize: 24),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
counter++;
});
},
child: Text('Increment Counter'),
),
],
),
),
);
}
}

53

You might also like