Flutter Assignment 2
Flutter Assignment 2
Key aspects of mobile app development include user interface (UI) design,
ensuring the app is visually appealing and easy to use; functionality, which
ensures the app meets user needs; and performance, ensuring the app runs
smoothly and efficiently. Security and scalability are also crucial to protect user
data and handle growing demand.
1
Mobile App Development
Assignment 1 - Develop a Flutter app using Dart programming that allows users to convert
temperatures between Celsius, Fahrenheit, and Kelvin. The app should include an input field for
the temperature value, drop-down menus to select the input and output units, and a button to
perform the conversion. Display the converted temperature result within the app's interface.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(TemperatureConverterApp());
}
class TemperatureConverterApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Temperature Converter',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: TemperatureConverter(),
);
}
}
class TemperatureConverter extends StatefulWidget {
@override
_TemperatureConverterState createState() => _TemperatureConverterState();
}
class _TemperatureConverterState extends State<TemperatureConverter> {
final TextEditingController _controller = TextEditingController();
String _fromUnit = 'Celsius';
String _toUnit = 'Fahrenheit';
String _result = '';
final List<String> _units = ['Celsius', 'Fahrenheit', 'Kelvin'];
void _convertTemperature() {
double? input = double.tryParse(_controller.text);
if (input == null) {
setState(() {
_result = 'Please enter a valid number';
});
return;
}
double output;
2
Mobile App Development
if (_fromUnit == _toUnit) {
output = input;
} else if (_fromUnit == 'Celsius' && _toUnit == 'Fahrenheit') {
output = (input * 9 / 5) + 32;
} else if (_fromUnit == 'Celsius' && _toUnit == 'Kelvin') {
output = input + 273.15;
} else if (_fromUnit == 'Fahrenheit' && _toUnit == 'Celsius') {
output = (input - 32) * 5 / 9;
} else if (_fromUnit == 'Fahrenheit' && _toUnit == 'Kelvin') {
output = (input - 32) * 5 / 9 + 273.15;
} else if (_fromUnit == 'Kelvin' && _toUnit == 'Celsius') {
output = input - 273.15;
} else if (_fromUnit == 'Kelvin' && _toUnit == 'Fahrenheit') {
output = (input - 273.15) * 9 / 5 + 32;
} else {
output = input; // Should never happen
}
setState(() {
_result = '$_fromUnit to $_toUnit: ${output.toStringAsFixed(2)}';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Temperature Converter'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _controller,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Enter Temperature',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
3
Mobile App Development
Expanded(
child: DropdownButtonFormField<String>(
value: _fromUnit,
decoration: InputDecoration(
labelText: 'From',
border: OutlineInputBorder(),
),
items: _units.map((unit) {
return DropdownMenuItem(
value: unit,
child: Text(unit),
);
}).toList(),
onChanged: (value) {
setState(() {
_fromUnit = value!;
});
},
),
),
SizedBox(width: 16),
Expanded(
child: DropdownButtonFormField<String>(
value: _toUnit,
decoration: InputDecoration(
labelText: 'To',
border: OutlineInputBorder(),
),
items: _units.map((unit) {
return DropdownMenuItem(
value: unit,
child: Text(unit),
);
}).toList(),
onChanged: (value) {
setState(() {
_toUnit = value!;
});
},
),
),
],
),
SizedBox(height: 16),
4
Mobile App Development
ElevatedButton(
onPressed: _convertTemperature,
child: Text('Convert'),
),
SizedBox(height: 16),
Text(
_result,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
Output -
5
Mobile App Development
Assignment 2 - Develop a Flutter app using Dart programming to calculate the Body Mass
Index (BMI) based on user input for weight and height. The app should include input fields for
users to enter their weight (in kilograms) and height (in centimetres), a button to trigger the
BMI calculation, and a display area for the BMI result along with its classification (e.g.,
Underweight, Normal weight, Overweight, Obese). Ensure that the app runs in Android Studio
and provides a user-friendly interface. If BMI < 18.5 show underweight, BMI 18.5<=24.9 show
normal weight, and BMI 24.9<= 29.9 show overweight, else obese.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(BMICalculatorApp());
}
class BMICalculatorApp extends StatelessWidget {
const BMICalculatorApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'BMI Calculator',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BMICalculator(),
);
}
}
class BMICalculator extends StatefulWidget {
const BMICalculator({super.key});
@override
_BMICalculatorState createState() => _BMICalculatorState();
}
class _BMICalculatorState extends State<BMICalculator> {
final TextEditingController _weightController = TextEditingController();
final TextEditingController _heightController = TextEditingController();
String _result = '';
void _calculateBMI() {
double? weight = double.tryParse(_weightController.text);
double? height = double.tryParse(_heightController.text);
if (weight == null || height == null || height <= 0) {
setState(() {
6
Mobile App Development
7
Mobile App Development
decoration: InputDecoration(
labelText: 'Enter Height (cm)',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: _calculateBMI,
child: Text('Calculate BMI'),
),
SizedBox(height: 16),
Text(
_result,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
8
Mobile App Development
Output -
9
Mobile App Development
Assignment 3 - Create a Flutter app using Dart programming that calculates a person's age
based on their date of birth. The app should include an input field for users to enter their date
of birth in the format (yyyy-mm-dd), a button to trigger the age calculation, and a display area
to show the calculated age. Ensure that the app runs in Android Studio and provides a user-
friendly interface.
Code (main.dart) -
import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; // For date formatting
void main() {
runApp(const AgeCalculatorApp());
}
class AgeCalculatorApp extends StatelessWidget {
const AgeCalculatorApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Age Calculator',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const AgeCalculatorScreen(),
);
}
}
class AgeCalculatorScreen extends StatefulWidget {
const AgeCalculatorScreen({super.key});
@override
_AgeCalculatorScreenState createState() => _AgeCalculatorScreenState();
}
class _AgeCalculatorScreenState extends State<AgeCalculatorScreen> {
final TextEditingController _dobController = TextEditingController();
String _calculatedAge = '';
void _calculateAge() {
try {
final dob = DateFormat('yyyy-MM-dd').parse(_dobController.text);
final today = DateTime.now();
int years = today.year - dob.year;
int months = today.month - dob.month;
int days = today.day - dob.day;
if (days < 0) {
10
Mobile App Development
months -= 1;
days += DateTime(today.year, today.month, 0).day;
}
if (months < 0) {
years -= 1;
months += 12;
}
setState(() {
_calculatedAge = '$years years, $months months, $days days';
});
} catch (e) {
setState(() {
_calculatedAge = 'Invalid date format. Please use yyyy-mm-dd.';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Age Calculator'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _dobController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter your date of birth (yyyy-mm-dd)',
),
keyboardType: TextInputType.datetime,
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _calculateAge,
child: const Text('Calculate Age'),
),
const SizedBox(height: 20),
Text(
11
Mobile App Development
_calculatedAge,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
Output -
12
Mobile App Development
Assignment 4 - Develop a Flutter app using Dart programming that functions as a stopwatch
with start, stop, and reset functionalities. The app should include a display area for the elapsed
time, buttons to start, stop, and reset the stopwatch, and should provide a user-friendly
interface. Ensure that the app runs in Android Studio and updates the elapsed time in real-time
while the stopwatch is running.
Code (main.dart) -
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(const StopwatchApp());
}
class StopwatchApp extends StatelessWidget {
const StopwatchApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Stopwatch',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const StopwatchScreen(),
);
}
}
class StopwatchScreen extends StatefulWidget {
const StopwatchScreen({super.key});
@override
_StopwatchScreenState createState() => _StopwatchScreenState();
}
class _StopwatchScreenState extends State<StopwatchScreen> {
late Stopwatch _stopwatch;
late Timer _timer;
String _formattedTime = '00:00.00';
@override
void initState() {
super.initState();
_stopwatch = Stopwatch();
}
void _startStopwatch() {
if (!_stopwatch.isRunning) {
13
Mobile App Development
_stopwatch.start();
_timer = Timer.periodic(const Duration(milliseconds: 1), (timer) {
setState(() {
_formattedTime = _formatTime(_stopwatch.elapsed);
});
});
}
}
void _stopStopwatch() {
if (_stopwatch.isRunning) {
_stopwatch.stop();
_timer.cancel();
}
}
void _resetStopwatch() {
_stopwatch.reset();
setState(() {
_formattedTime = '00:00.00';
});
}
String _formatTime(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final minutes = twoDigits(duration.inMinutes.remainder(60));
final seconds = twoDigits(duration.inSeconds.remainder(60));
final milliseconds = twoDigits(duration.inMilliseconds.remainder(100));
return '$minutes:$seconds.$milliseconds';
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Stopwatch'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_formattedTime,
style: const TextStyle(
fontSize: 48,
14
Mobile App Development
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 40),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _startStopwatch,
child: const Text('Start'),
),
ElevatedButton(
onPressed: _stopStopwatch,
child: const Text('Stop'),
),
ElevatedButton(
onPressed: _resetStopwatch,
child: const Text('Reset'),
),
],
),
],
),
),
);
}
@override
void dispose() {
if (_timer.isActive) {
_timer.cancel();
}
super.dispose();
}
}
15
Mobile App Development
Output -
Assignment 5 - Develop a Flutter app using Dart programming that creates a list of names for
individuals eligible to vote. The app should take input from the user, including names and ages,
16
Mobile App Development
and use toList and map to filter and display two separate lists: one for those who are eligible to
vote and one for those who are not eligible. Ensure that the app runs in Android Studio and
provides a clear and user-friendly interface to show both lists based on the eligibility criteria .
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(const VoterEligibilityApp());
}
class VoterEligibilityApp extends StatelessWidget {
const VoterEligibilityApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Voter Eligibility',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const VoterEligibilityScreen(),
);
}
}
class VoterEligibilityScreen extends StatefulWidget {
const VoterEligibilityScreen({super.key});
@override
_VoterEligibilityScreenState createState() => _VoterEligibilityScreenState();
}
class _VoterEligibilityScreenState extends State<VoterEligibilityScreen> {
final TextEditingController _nameController = TextEditingController();
final TextEditingController _ageController = TextEditingController();
final List<Map<String, dynamic>> _people = [];
List<Map<String, dynamic>> _eligible = [];
List<Map<String, dynamic>> _notEligible = [];
void _addPerson() {
final String name = _nameController.text;
final String ageText = _ageController.text;
if (name.isNotEmpty && int.tryParse(ageText) != null) {
final int age = int.parse(ageText);
setState(() {
_people.add({'name': name, 'age': age});
_filterEligibility();
17
Mobile App Development
});
_nameController.clear();
_ageController.clear();
}
}
void _filterEligibility() {
setState(() {
_eligible = _people.where((person) => person['age'] >= 18).toList();
_notEligible = _people.where((person) => person['age'] < 18).toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Voter Eligibility'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _nameController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Name',
),
),
const SizedBox(height: 10),
TextField(
controller: _ageController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Age',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: _addPerson,
child: const Text('Add Person'),
),
18
Mobile App Development
19
Mobile App Development
Expanded(
child: ListView.builder(
itemCount: _notEligible.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_notEligible[index]['name']),
subtitle:
Text('Age: ${_notEligible[index]['age']}'),
);
},
),
),
],
),
),
],
),
),
],
),
),
);
}
}
Output -
20
Mobile App Development
21
Mobile App Development
runs seamlessly in Android Studio and provides a user-friendly interface for users to interact
with the countdown timer.
Code (maint.dart) -
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(const CountdownTimerApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Countdown Timer',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const CountdownTimerScreen(),
);
}
}
@override
_CountdownTimerScreenState createState() => _CountdownTimerScreenState();
}
void _startTimer() {
final int? totalSeconds = int.tryParse(_timeController.text);
if (totalSeconds != null && totalSeconds > 0) {
setState(() {
_remainingTime = Duration(seconds: totalSeconds);
22
Mobile App Development
});
_timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (_remainingTime.inSeconds > 0) {
setState(() {
_remainingTime -= const Duration(seconds: 1);
});
} else {
timer.cancel();
}
});
}
}
void _stopTimer() {
_timer?.cancel();
}
void _resetTimer() {
_stopTimer();
setState(() {
_remainingTime = const Duration();
_timeController.clear();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Countdown Timer'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
23
Mobile App Development
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _timeController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Enter Time in Seconds',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 20),
Text(
_formatTime(_remainingTime),
style: const TextStyle(
fontSize: 48,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _startTimer,
child: const Text('Start'),
),
ElevatedButton(
onPressed: _stopTimer,
child: const Text('Stop'),
),
ElevatedButton(
onPressed: _resetTimer,
child: const Text('Reset'),
),
],
),
],
),
),
);
}
24
Mobile App Development
@override
void dispose() {
_timer?.cancel();
_timeController.dispose();
super.dispose();
}
}
Output -
Assignment 7 - Develop a Flutter app using Dart programming that converts one currency to
another based on user input and predefined exchange rates. The app should include input fields
for users to enter the amount, drop-down menus to select the input and output currencies, and
a button to perform the conversion. Ensure that the app displays the converted amount and
provides a user-friendly interface. The app should run seamlessly in Android Studio.
25
Mobile App Development
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(const CurrencyConverterApp());
}
class CurrencyConverterApp extends StatelessWidget {
const CurrencyConverterApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Currency Converter',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const CurrencyConverterScreen(),
);
}
}
class CurrencyConverterScreen extends StatefulWidget {
const CurrencyConverterScreen({super.key});
@override
_CurrencyConverterScreenState createState() =>
_CurrencyConverterScreenState();
}
class _CurrencyConverterScreenState extends State<CurrencyConverterScreen> {
final TextEditingController _amountController = TextEditingController();
final Map<String, double> _exchangeRates = {
'USD': 1.0,
'EUR': 0.95,
'JPY': 156.12,
'GBP': 0.80,
'INR': 86.21,
};
String _fromCurrency = 'USD';
String _toCurrency = 'EUR';
String _convertedAmount = '';
void _convertCurrency() {
final String amountText = _amountController.text;
if (amountText.isNotEmpty && double.tryParse(amountText) != null) {
final double amount = double.parse(amountText);
final double fromRate = _exchangeRates[_fromCurrency]!;
26
Mobile App Development
27
Mobile App Development
_fromCurrency = value!;
});
},
decoration: const InputDecoration(
labelText: 'From',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 10),
Expanded(
child: DropdownButtonFormField<String>(
value: _toCurrency,
items: _exchangeRates.keys
.map((currency) => DropdownMenuItem(
value: currency,
child: Text(currency),
))
.toList(),
onChanged: (value) {
setState(() {
_toCurrency = value!;
});
},
decoration: const InputDecoration(
labelText: 'To',
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _convertCurrency,
child: const Text('Convert'),
),
const SizedBox(height: 20),
Text(
_convertedAmount.isNotEmpty
? 'Converted Amount: $_convertedAmount $_toCurrency'
: 'Enter amount and select currencies',
style: const TextStyle(
fontSize: 18,
28
Mobile App Development
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
],
),
),
);
}
@override
void dispose() {
_amountController.dispose();
super.dispose();
}
}
Output -
29
Mobile App Development
Assignment 8 - Create a Flutter app using Dart programming that calculates the tip amount
based on the bill total and the selected tip percentage. The app should include input fields for
users to enter the bill amount, options to select the tip percentage, and buttons to calculate the
tip and reset the data. Ensure that the app displays the calculated tip amount and the total bill,
30
Mobile App Development
uses Indian currency (INR), and runs seamlessly in Android Studio, providing a user-friendly
interface.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(TipCalculatorApp());
}
class TipCalculatorApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Tip Calculator',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: TipCalculatorScreen(),
);
}
}
class TipCalculatorScreen extends StatefulWidget {
@override
_TipCalculatorScreenState createState() => _TipCalculatorScreenState();
}
class _TipCalculatorScreenState extends State<TipCalculatorScreen> {
final TextEditingController _billController = TextEditingController();
double _tipPercentage = 10;
double _calculatedTip = 0;
double _totalBill = 0;
void _calculateTip() {
double billAmount = double.tryParse(_billController.text) ?? 0;
setState(() {
_calculatedTip = (billAmount * _tipPercentage) / 100;
_totalBill = billAmount + _calculatedTip;
});
}
void _reset() {
setState(() {
_billController.clear();
_tipPercentage = 10;
_calculatedTip = 0;
_totalBill = 0;
31
Mobile App Development
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Tip Calculator'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _billController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Bill Amount (₹)',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
Text(
'Tip Percentage: ${_tipPercentage.toStringAsFixed(0)}%',
style: TextStyle(fontSize: 16),
),
Slider(
value: _tipPercentage,
min: 0,
max: 100,
divisions: 20,
label: _tipPercentage.toStringAsFixed(0),
onChanged: (value) {
setState(() {
_tipPercentage = value;
});
},
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _calculateTip,
32
Mobile App Development
child: Text('Calculate'),
),
ElevatedButton(
onPressed: _reset,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
child: Text('Reset'),
),
],
),
SizedBox(height: 24),
Text(
'Calculated Tip: ₹${_calculatedTip.toStringAsFixed(2)}',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 8),
Text(
'Total Bill: ₹${_totalBill.toStringAsFixed(2)}',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
],
),
),
);
}
}
Output -
33
Mobile App Development
Assignment 9 - Develop a Flutter app using Dart programming to calculate the area and
circumference of a circle based on the input radius. The app should provide a dropdown list for
users to select either the area or circumference calculation. Ensure that the app displays the
calculated result and runs seamlessly in Android Studio, providing a user-friendly interface .
34
Mobile App Development
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(CircleCalculatorApp());
}
class CircleCalculatorApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Circle Calculator',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: CircleCalculatorScreen(),
);
}
}
class CircleCalculatorScreen extends StatefulWidget {
@override
_CircleCalculatorScreenState createState() => _CircleCalculatorScreenState();
}
class _CircleCalculatorScreenState extends State<CircleCalculatorScreen> {
final TextEditingController _radiusController = TextEditingController();
String _selectedCalculation = 'Area';
double _result = 0;
void _calculate() {
double radius = double.tryParse(_radiusController.text) ?? 0;
setState(() {
if (_selectedCalculation == 'Area') {
_result = 3.14159 * radius * radius;
} else if (_selectedCalculation == 'Circumference') {
_result = 2 * 3.14159 * radius;
}
});
}
void _reset() {
setState(() {
_radiusController.clear();
_selectedCalculation = 'Area';
_result = 0;
35
Mobile App Development
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Circle Calculator'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _radiusController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Radius',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
DropdownButtonFormField<String>(
value: _selectedCalculation,
items: ['Area', 'Circumference']
.map((calculation) => DropdownMenuItem(
value: calculation,
child: Text(calculation),
))
.toList(),
onChanged: (value) {
setState(() {
_selectedCalculation = value!;
});
},
decoration: InputDecoration(
labelText: 'Calculation Type',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
36
Mobile App Development
ElevatedButton(
onPressed: _calculate,
child: Text('Calculate'),
),
ElevatedButton(
onPressed: _reset,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
child: Text('Reset'),
),
],
),
SizedBox(height: 24),
Text(
'Result: ${_result.toStringAsFixed(2)}',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
],
),
),
);
}
}
Output -
37
Mobile App Development
Assignment 10 - Develop a flashcards app using Flutter and Dart programming that allows
users to add questions and answers. The app should enable users to review the flashcards they
have created. Ensure that the app runs seamlessly in Android Studio and provides a user-
friendly interface for managing and reviewing flashcards.
38
Mobile App Development
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(FlashcardsApp());
}
class FlashcardsApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flashcards App',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: FlashcardsScreen(),
);
}
}
class FlashcardsScreen extends StatefulWidget {
@override
_FlashcardsScreenState createState() => _FlashcardsScreenState();
}
class _FlashcardsScreenState extends State<FlashcardsScreen> {
final List<Map<String, String>> _flashcards = [];
final TextEditingController _questionController = TextEditingController();
final TextEditingController _answerController = TextEditingController();
void _addFlashcard() {
if (_questionController.text.isNotEmpty && _answerController.text.isNotEmpty) {
setState(() {
_flashcards.add({
'question': _questionController.text,
'answer': _answerController.text,
});
_questionController.clear();
_answerController.clear();
});
}
}
void _resetFlashcards() {
setState(() {
_flashcards.clear();
39
Mobile App Development
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flashcards App'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _questionController,
decoration: InputDecoration(
labelText: 'Question',
border: OutlineInputBorder(),
),
),
SizedBox(height: 8),
TextField(
controller: _answerController,
decoration: InputDecoration(
labelText: 'Answer',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: _addFlashcard,
child: Text('Add Flashcard'),
),
ElevatedButton(
onPressed: _resetFlashcards,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
child: Text('Reset'),
),
],
40
Mobile App Development
),
SizedBox(height: 24),
Expanded(
child: ListView.builder(
itemCount: _flashcards.length,
itemBuilder: (context, index) {
final flashcard = _flashcards[index];
return Card(
margin: EdgeInsets.symmetric(vertical: 8),
child: ListTile(
title: Text('Q: ${flashcard['question']}'),
subtitle: Text('A: ${flashcard['answer']}'),
),
);
},
),
),
],
),
),
);
}
}
Output -
41
Mobile App Development
Assignment 11 - Develop a single-page app using Flutter with the following features:
a. An AppBar displaying the app name as "Barbecue Station."
b. A side drawer with the name "Cuisine List."
42
Mobile App Development
c. A floating action button that, when clicked, navigates to a page displaying pictures of pizza.
Ensure the app runs seamlessly in Android Studio and provides a user-friendly interface.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(BarbecueStationApp());
}
class BarbecueStationApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Barbecue Station',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Barbecue Station'),
),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Colors.teal,
),
child: Text(
'Cuisine List',
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
43
Mobile App Development
),
),
ListTile(
leading: Icon(Icons.fastfood),
title: Text('Pizza'),
onTap: () {},
),
ListTile(
leading: Icon(Icons.local_dining),
title: Text('BBQ Ribs'),
onTap: () {},
),
],
),
),
body: Center(
child: Text(
'Welcome to Barbecue Station!',
style: TextStyle(fontSize: 18),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PizzaPage(),
),
);
},
child: Icon(Icons.photo),
),
);
}
}
class PizzaPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Pizza Gallery'),
),
body: GridView.count(
crossAxisCount: 2,
44
Mobile App Development
padding: EdgeInsets.all(16),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
children: List.generate(6, (index) {
return Card(
elevation: 4,
child: Image.network(
'https://media.istockphoto.com/id/1442417585/photo/person-getting-a-piece-of-
cheesy-pepperoni-pizza.jpg?
s=612x612&w=0&k=20&c=k60TjxKIOIxJpd4F4yLMVjsniB4W1BpEV4Mi_nb4uJU=',
fit: BoxFit.cover,
));
}),
),
);
}
}
Output -
45
Mobile App Development
46
Mobile App Development
47
Mobile App Development
Assignment 12 - Develop a Flutter app using Dart programming that displays 10 hardcoded
random names upon clicking a button. Include another button that navigates to a different
page. Ensure the app runs seamlessly in Android Studio and provides a user-friendly interface .
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(RandomNamesApp());
}
class RandomNamesApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Random Names App',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: RandomNamesPage(),
);
}
}
class RandomNamesPage extends StatefulWidget {
@override
_RandomNamesPageState createState() => _RandomNamesPageState();
}
class _RandomNamesPageState extends State<RandomNamesPage> {
final List<String> _names = [
"Fardeen",
"Pramit",
"Ayan",
"Ekram",
"Kaustav",
"Raj",
"Akash",
"Atrick",
"Selmon",
"Rajat"
];
List<String> _displayedNames = [];
void _showRandomNames() {
setState(() {
48
Mobile App Development
_displayedNames = List.from(_names)..shuffle();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Random Names App'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ElevatedButton(
onPressed: _showRandomNames,
child: Text('Show Random Names'),
),
SizedBox(height: 16),
Expanded(
child: ListView.builder(
itemCount: _displayedNames.length,
itemBuilder: (context, index) {
return Card(
margin: EdgeInsets.symmetric(vertical: 8),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
_displayedNames[index],
style: TextStyle(fontSize: 18),
),
),
);
},
),
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondPage(),
),
49
Mobile App Development
);
},
child: Text('Go to Next Page'),
),
],
),
),
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Page'),
),
body: Center(
child: Text(
'Welcome to the second page!',
style: TextStyle(fontSize: 18),
),
),
);
}
}
50
Mobile App Development
Output -
51
Mobile App Development
52
Mobile App Development
Assignment 13 - Develop a Flutter app using a stateful widget that changes the AppBar name
when the user enters a name. The app should include an input field for the user to enter their
name, and the AppBar title should update accordingly. Ensure the app runs seamlessly in
Android Studio and provides a user-friendly interface.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(DynamicAppBarApp());
}
class DynamicAppBarApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Dynamic AppBar App',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: DynamicAppBarPage(),
);
}
}
class DynamicAppBarPage extends StatefulWidget {
@override
_DynamicAppBarPageState createState() => _DynamicAppBarPageState();
}
class _DynamicAppBarPageState extends State<DynamicAppBarPage> {
String _appBarTitle = 'Dynamic AppBar';
final TextEditingController _nameController = TextEditingController();
void _updateAppBarTitle() {
setState(() {
_appBarTitle = _nameController.text.isNotEmpty ? _nameController.text : 'Dynamic AppBar';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(_appBarTitle),
),
body: Padding(
53
Mobile App Development
54
Mobile App Development
Output -
55
Mobile App Development
Assignment 14 - Develop a Flutter app with a login page that includes the following validation
rules:
a. The username must be at least 6 characters long.
b. The email should be valid.
c. The password must contain: i. An uppercase letter ii. A lowercase letter iii. Digits iv. A special
character v. More than 6 characters
The login button should be displayed, and when clicked, it should show any validation errors if
present. Ensure the app runs seamlessly in Android Studio and provides a user-friendly
interface.
Code (main.dart) -
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Login Validation',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const LoginPage(),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage({Key? key}) : super(key: key);
@override
State<LoginPage> createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final _formKey = GlobalKey<FormState>();
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
String? _validateUsername(String? value) {
if (value == null || value.isEmpty) {
56
Mobile App Development
57
Mobile App Development
children: [
TextFormField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
),
validator: _validateUsername,
),
const SizedBox(height: 16.0),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
),
validator: _validateEmail,
keyboardType: TextInputType.emailAddress,
),
const SizedBox(height: 16.0),
TextFormField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
),
obscureText: true,
validator: _validatePassword,
),
const SizedBox(height: 32.0),
Center(
child: ElevatedButton(
onPressed: _onLoginPressed,
child: const Text('Login'),
),
),
],
),
),
),
);
}
}
58
Mobile App Development
Output -
59
Mobile App Development
60
Mobile App Development
Assignment 15 - Develop a Flutter app with a button that animates a Container's width,
height, and colour over a period of 1 second when pressed. The container should initially have a
width and height of 100.0 and a colour of red. When the button is pressed, the container should
animate to a width of 200.0, height of 200.0, and colour of blue. Ensure the app runs seamlessly
in Android Studio and provides a visually engaging animation.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Animated Container',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const AnimatedContainerPage(),
);
}
}
@override
State<AnimatedContainerPage> createState() => _AnimatedContainerPageState();
}
void _animateContainer() {
setState(() {
61
Mobile App Development
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Animated Container'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedContainer(
width: _width,
height: _height,
color: _color,
duration: const Duration(seconds: 1),
curve: Curves.easeInOut,
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: _animateContainer,
child: const Text('Animate'),
),
],
),
),
);
}
}
62
Mobile App Development
Output -
63
Mobile App Development
Assignment 16 – Develop a simple Flutter app that includes two images. Utilize the
AnimatedCrossFade widget to create a smooth transition between the two images when a
button is pressed. Ensure the app runs seamlessly in Android Studio and provides a visually
engaging experience.
Code (main.dart) -
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Animated CrossFade Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const AnimatedCrossFadePage(),
);
}
}
@override
State<AnimatedCrossFadePage> createState() => _AnimatedCrossFadePageState();
}
void _toggleCrossFade() {
setState(() {
_showFirstImage = !_showFirstImage;
});
}
64
Mobile App Development
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Animated CrossFade Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedCrossFade(
firstChild:
Image.asset('assets/image1.png', width: 300, height: 300),
secondChild:
Image.asset('assets/image2.png', width: 300, height: 300),
crossFadeState: _showFirstImage
? CrossFadeState.showFirst
: CrossFadeState.showSecond,
duration: const Duration(seconds: 1),
),
const SizedBox(height: 20.0),
ElevatedButton(
onPressed: _toggleCrossFade,
child: const Text('Toggle Images'),
),
],
),
),
);
}
}
65
Mobile App Development
Output -
66