Flutter Lab Manual
Flutter Lab Manual
Flutter Lab Manual
(R22 Regulation)
LAB MANUAL
1
INDEX
a)Install Flutter and Dart SDK. 1
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.
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 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.,
. Click File
Installation in MacOS
To install Flutter on MacOS, you will have to follow the following steps:
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 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.,
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
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:
void main() {
// Variables
print("Hello, $name!");
print("Age: $age");
// Function
return a + b;
// Calling a function
print("Sum: $result");
// Conditional statement
print("$name is an adult.");
1
} else {
print("$name is a minor.");
// Loop
print("Count: $i");
// List
print("Fruits: $fruits");
// Map
"name": "Alice",
"age": "30",
"job": "Engineer",
};
print("Person: $person");
OUTPUT :
Hello, John!
Age: 25
2
Is a student? true
Sum: 15
John is an adult.
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
3
2 a) Explore various Flutter widgets(Text, Image, Container, etc.).
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Text Widget
Text(
'Hello, Flutter!',
),
// 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',
),
),
],
),
),
),
);
OUTPUT:
5
3a) Design a responsive UI that adapts to different screen sizes.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
home: ResponsiveUI(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: LayoutBuilder(
6
double screenWidth = constraints.maxWidth;
return LargeScreenLayout();
} else {
return SmallScreenLayout();
},
),
);
@override
return Center(
child: Container(
width: 600,
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
7
'Welcome to the Large Screen Layout!',
),
SizedBox(height: 20),
FlutterLogo(size: 150),
],
),
),
);
@override
return Center(
child: Container(
padding: EdgeInsets.all(16),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
),
SizedBox(height: 20),
8
FlutterLogo(size: 100),
],
),
),
);
OUTPUT:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
9
return MaterialApp(
home: ResponsiveUI(),
);
@override
// Determine breakpoints
if (isSmallScreen) {
return SmallScreenLayout();
} else if (isMediumScreen) {
return MediumScreenLayout();
} else {
return LargeScreenLayout();
10
}
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(height: 20),
FlutterLogo(size: 100),
],
),
),
);
@override
11
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(height: 20),
FlutterLogo(size: 150),
],
),
),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
12
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
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());
@override
return MaterialApp(
home: HomeScreen(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
14
Navigator.push(
context,
);
},
),
),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
),
),
15
);
OUTPUT:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
routes: {
16
},
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/second');
},
),
),
);
17
class SecondScreen extends StatelessWidget {
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.popAndPushNamed(context, '/');
},
),
),
);
18
5 a) write a program state-ful and stateless widgets.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// 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(),
),
);
}
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'),
),
],
),
],
),
),
);
}
}
void incrementCounter() {
_counter++;
notifyListeners();
}
void decrementCounter() {
_counter--;
notifyListeners();
}
}
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());
}
@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,
),
),
);
}
}
@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());
@override
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
),
buttonTheme: ButtonThemeData(
),
26
),
home: StyledApp(),
);
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
style: Theme.of(context).textTheme.headline1,
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
},
),
27
],
),
),
);
OUTPUT :
void main() {
runApp(MyApp());
@override
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyForm(),
28
);
@override
@override
return Scaffold(
appBar: AppBar(
),
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
29
children: [
TextFormField(
decoration: InputDecoration(
labelText: 'Name',
),
validator: (value) {
return null;
},
onSaved: (value) {
name = value!;
},
),
SizedBox(height: 16),
TextFormField(
decoration: InputDecoration(
labelText: 'Email',
),
validator: (value) {
return null;
30
},
onSaved: (value) {
email = value!;
},
),
SizedBox(height: 16),
TextFormField(
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
),
validator: (value) {
return null;
},
onSaved: (value) {
password = value!;
},
),
SizedBox(height: 16),
DropdownButtonFormField<String>(
value: selectedCountry,
onChanged: (value) {
setState(() {
31
selectedCountry = value!;
});
},
.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();
},
child: Text('Submit'),
),
],
),
),
32
),
);
OUTPUT:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
33
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyForm(),
);
@override
@override
return Scaffold(
appBar: AppBar(
34
),
body: Padding(
padding: EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
decoration: InputDecoration(
labelText: 'Name',
),
validator: (value) {
return null;
},
onSaved: (value) {
name = value!;
},
),
SizedBox(height: 16),
TextFormField(
decoration: InputDecoration(
35
labelText: 'Email',
),
validator: (value) {
if (!RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$').hasMatch(value)) {
return null;
},
onSaved: (value) {
email = value!;
},
),
SizedBox(height: 16),
TextFormField(
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
),
validator: (value) {
36
}
return null;
},
onSaved: (value) {
password = value!;
},
),
SizedBox(height: 16),
DropdownButtonFormField<String>(
value: selectedCountry,
onChanged: (value) {
setState(() {
selectedCountry = value!;
});
},
.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();
},
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());
@override
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyAnimatedUI(),
);
@override
39
double _containerWidth = 100.0;
void _animateContainer() {
setState(() {
});
@override
return Scaffold(
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedContainer(
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,
),
],
),
),
);
OUTPUT:
41
8 b) Experiment with different types of animations(fade , slide, etc
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
@override
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyAnimatedUI(),
);
@override
42
class _MyAnimatedUIState extends State<MyAnimatedUI> {
void _toggleFade() {
setState(() {
_isFadeVisible = !_isFadeVisible;
});
void _toggleSlide() {
setState(() {
_isSlideVisible = !_isSlideVisible;
});
void _toggleScale() {
setState(() {
_isScaleVisible = !_isScaleVisible;
});
@override
return Scaffold(
43
appBar: AppBar(
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedOpacity(
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>(
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,
).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,
),
ElevatedButton(
onPressed: _toggleSlide,
),
ElevatedButton(
onPressed: _toggleScale,
),
],
),
],
),
),
);
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());
}
@override
void initState() {
super.initState();
_fetchData();
}
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:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
49
}
@override
void initState() {
super.initState();
_fetchData();
}
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:
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));
MockClient(this.onRequest);
@override
Future<http.Response> send(http.BaseRequest request) async {
onRequest(MockClientRequest(request));
return http.Response(jsonEncode({'error': 'Not Implemented'}), 500);
}
}
@override
final Map<String, String> headers = {};
}
OUTPUT:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
52
title: 'Debugging Example',
home: MyHomePage(),
);
}
}
@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