MOBILE APPLICATION DEVELOPMENT (BCA)


FLUTTER MOBILE APPLICATION DEVELOPMENT

                                            - Thirumurugan , BCA
t.h.i.r.u_10



1. To use GUI components, Font and Colours

 import 'package:flutter/material.dart';

void main() {

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter GUI Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            const Text(
              'Headline Text',
              style: TextStyle(
                fontSize: 32.0,
                fontWeight: FontWeight.bold,
                color: Colors.blue,
              ),
            ),
            const SizedBox(height: 20),
            const Text(
              'This is a body text. It is styled directly in the widget.',
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.black,
              ),
            ),
            const SizedBox(height: 20),
            Text(
              'This is another body text with different styling.',
              style: TextStyle(
                fontSize: 16.0,
                color: Colors.grey[700],
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {},
              child: const Text('Click Me'),
            )
          ],
        ),
      ),
    );
  }
}



2. To use Layout Managers.

 


import 'package:flutter/material.dart'; 

void main() {

 runApp(const MyApp()); } 

class MyApp extends StatelessWidget {

 const MyApp({super.key}); 

@override 

Widget build(BuildContext context) { 

return const MaterialApp( title: 'Flutter Layout Demo', home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { 

const MyHomePage({super.key}); @override Widget build(BuildContext context) { 

return Scaffold( appBar: AppBar( title: const Text('Flutter Layout Demo'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const Text( 'Column Layout', style: TextStyle( fontSize: 24.0, fontWeight: FontWeight.bold, color: Colors.blue, ), ), const SizedBox(height: 20), const Column(

crossAxisAlignment: CrossAxisAlignment.start,

children: <Widget>[

Text('Item 1'),

Text('Item 2'),

Text('Item 3'),

],

),

const SizedBox(height: 20),

const Text(

'Row Layout',

style: TextStyle(

fontSize: 24.0,

fontWeight: FontWeight.bold,

color: Colors.blue,

),

),

const SizedBox(height: 20),

const Row(

mainAxisAlignment: MainAxisAlignment.spaceBetween,

children: <Widget>[

Text('Item 1'),

Text('Item 2'),

Text('Item 3'),

],

),

const SizedBox(height: 20),

const Text(

'Container Layout',

style: TextStyle(

fontSize: 24.0,

fontWeight: FontWeight.bold,

color: Colors.blue,

),

),

const SizedBox(height: 20),

Container(

padding: const EdgeInsets.all(16.0),

color: Colors.grey[300],

child: const Text(

'This is a container with padding and background color.'),

),

],

),

),

); 

}

}




3. To implement event listeners.

 

import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Event Listeners Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _text = '';
String _gestureMessage = 'No gesture detected';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Event Listeners Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const Text(
'Button Click',
style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
_text = 'Button Clicked!';
});
},
child: const Text('Click Me'),
),
const SizedBox(height: 20),
Text(
_text,
style: const TextStyle(fontSize: 18.0, color: Colors.black),
),
const SizedBox(height: 20),
const Text(
'Gesture Detection',
style: TextStyle(
fontSize: 24.0,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
),
const SizedBox(height: 20),
GestureDetector(
onTap: () {
setState(() {
_gestureMessage = 'Tap detected';
});
},
onDoubleTap: () {
setState(() {
_gestureMessage = 'Double tap detected';
});
},
onLongPress: () {
setState(() {
_gestureMessage = 'Long press detected';
});
},
child: Container(
width: double.infinity,
height: 100,
color: Colors.grey[300],
child: Center(
child: Text(
_gestureMessage,
style: const TextStyle(fontSize: 18.0, color: Colors.black),
),
),
),
),
],
),
),
);
}
}

4. To use image animations.

 

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Image Animation Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool _showFirstImage = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Image Animation Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedSwitcher(
duration: Duration(seconds: 1),
transitionBuilder: (Widget child, Animation<double> animation) {
return FadeTransition(opacity: animation, child: child);
},
child: _showFirstImage
? Image.network(
'https://picsum.photos/150?image=12',
key: ValueKey('image1'),
)
: Image.network(
'https://picsum.photos/300?image=10',
key: ValueKey('image2'),
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
setState(() {
_showFirstImage = !_showFirstImage;
});
},
child: Text('Switch Image'),
),
],
),
),
);
}
}

5. To draw basic graphical primitives on the screen.



 import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Drawing Primitives Demo',
home: PrimitivesScreen(),
);
}
}
class PrimitivesScreen extends StatefulWidget {
const PrimitivesScreen({super.key});
@override
State<PrimitivesScreen> createState() => _PrimitivesScreenState();
}
class _PrimitivesScreenState extends State<PrimitivesScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Drawing Primitives'),
),
body: Center(
child: CustomPaint(
size: const Size(300, 300),
painter: MyPainter(),
),
),
);
}
}
class MyPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..strokeWidth = 4.0;
// Draw a line
canvas.drawLine(
const Offset(0, 0),
Offset(size.width, size.height),
paint,
);
// Draw a rectangle
const rect = Rect.fromLTWH(50, 50, 100, 100);
paint.color = Colors.red;
canvas.drawRect(rect, paint);
// Draw a circle
final center = Offset(size.width / 2, size.height / 2);
const radius = 50.0;
paint.color = Colors.green;
canvas.drawCircle(center, radius, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) {
return false;
}
}

6. To make use of database

Add the lines sqflite: ^2.3.2 and path: ^1.8.3 under the cupertino_icons section
in the pubspec.yaml file.


import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Database Demo',
home: DatabaseScreen(),
);
}
}
class DatabaseScreen extends StatefulWidget {
const DatabaseScreen({super.key});
@override
State<DatabaseScreen> createState() => _DatabaseScreenState();
}
class _DatabaseScreenState extends State<DatabaseScreen> {
final DatabaseHelper dbHelper = DatabaseHelper();
List<Map<String, dynamic>> items = [];
int? editingItemId;
final _formKey = GlobalKey<FormState>();
final _editingController = TextEditingController();
@override
void initState() {
super.initState();
_refreshItems();
}
void _refreshItems() async {
final data = await dbHelper.queryAllRows();
setState(() {
items = data;
editingItemId = null;
});
}
void _addItem() async {
Map<String, dynamic> row = {
'name': 'Item ${items.length + 1}',
};
await dbHelper.insertItem(row);
_refreshItems();
}
void _updateItem(int id) async {
if (_formKey.currentState!.validate()) {
Map<String, dynamic> row = {
'id': id,
'name': _editingController.text,
};
await dbHelper.updateItem(row);
_refreshItems();
}
}
void _deleteItem(int id) async {
await dbHelper.deleteItem(id);
_refreshItems();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SQFLite Database'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
title: editingItemId == item['id']
? Form(
key: _formKey,
child: TextFormField(
controller: _editingController,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
)
: Text(item['name']),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(
editingItemId == item['id'] ? Icons.done : Icons.edit),
onPressed: () {
if (editingItemId == item['id']) {
_updateItem(item['id']);
} else {
setState(() {
editingItemId = item['id'];
_editingController.text = item['name'];
});
}
},
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
_deleteItem(item['id']);
},
),
],
),
);

},
),
floatingActionButton: FloatingActionButton(
onPressed: _addItem,
child: Icon(Icons.add),
),
);
}
}
class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
static Database? _database;
factory DatabaseHelper() {
return _instance;
}
DatabaseHelper._internal();
Future<Database> get database async {
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<Database> _initDatabase() async {
//path provider used
String path = join(await getDatabasesPath(), 'my_database.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future<void> _onCreate(Database db, int version) async {
await db.execute(
'CREATE TABLE items(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)',
);
}
Future<int> insertItem(Map<String, dynamic> row) async {
Database db = await database;
return await db.insert('items', row);
}
Future<List<Map<String, dynamic>>> queryAllRows() async {
Database db = await database;
return await db.query('items');
}
Future<int> updateItem(Map<String, dynamic> row) async {
Database db = await database;
int id = row['id'];
return await db.update('items', row, where: 'id = ?', whereArgs: [id]);
}
Future<int> deleteItem(int id) async {
Database db = await database;
return await db.delete('items', where: 'id = ?', whereArgs: [id]);
}
}


7. Notification Manager

Add the lines flutter_local_notifications: ^17.2.1+2 under the
cupertino_icons section in the pubspec.yaml file.
Add the line <uses-permission
android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> in the
AndroidManifest.xml file, within the <manifest> tag, just after the </application> tag.


Main.dart


import 'package:flutter/material.dart';
import 'package:practicals/NotificationManager/NotificationScreen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Notification Demo',
home: NotificationScreen(),
);
}
}
NotificationScreen.dart
import 'package:practicals/NotificationManager/NotificationHelper.dart';
import 'package:flutter/material.dart';
class NotificationScreen extends StatefulWidget {
const NotificationScreen({super.key});
@override
State<NotificationScreen> createState() => _NotificationScreenState();
}
class _NotificationScreenState extends State<NotificationScreen> {
final NotificationHelper _notificationHelper = NotificationHelper();
@override
void initState() {
super.initState();
_notificationHelper.initNotifications();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Notification'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_notificationHelper.showNotification();
},
child: Text('Show Notification'),
),
),
);
}
}
NotificationHelper.dart
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class NotificationHelper {
final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
Future<void> initNotifications() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
const InitializationSettings initializationSettings =
InitializationSettings(
android: initializationSettingsAndroid,
);
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
Future<void> showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your_channel_id',
'your_channel_name',
importance: Importance.max,
priority: Priority.high,
);
const NotificationDetails platformChannelSpecifics = NotificationDetails(
android: androidPlatformChannelSpecifics,
);
await _flutterLocalNotificationsPlugin.show(
0,
'Hello',
'This is a notification',
platformChannelSpecifics,
);
}
}



8. To use Multi threading

import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Notification Demo',
home: MultiThreadPage(),
);
}
}
class MultiThreadPage extends StatefulWidget {
const MultiThreadPage({super.key});
@override
State<MultiThreadPage> createState() => _MultiThreadPageState();
}
class _MultiThreadPageState extends State<MultiThreadPage> {
String _result = "Press the button";
Future<void> _performAsyncTask() async {
// Simulating a time-consuming task
await Future.delayed(Duration(seconds: 5));
setState(() {
_result = "Task completed!";
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Multi Thread'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: ElevatedButton(
onPressed: () {
_performAsyncTask();
setState(() {
_result = "Task in progress...";
});
},
child: Text('Start Task'),
),
),
SizedBox(height: 20),
Text(_result),
],
),
);
}
}


9. To use GPS location

information
Add the lines geolocator: ^10.1.0 under the cupertino_icons section in the
pubspec.yaml file.
Add the line <uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
in the AndroidManifest.xml file, within the <manifest> tag, just after the
</application> tag.


Main.dart 


import 'package:flutter/material.dart';
import 'package:practicals/Location/LocationScreen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter GPS Demo',
home: LocationScreen(),
);
}
}
LocationScreen.dart
import 'package:practicals/Location/LocationService.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LocationScreen extends StatefulWidget {
const LocationScreen({super.key});
@override
State<LocationScreen> createState() => _LocationScreenState();
}
class _LocationScreenState extends State<LocationScreen> {
Position? _currentPosition;
void _getCurrentLocation() async {
LocationService locationService = LocationService();
try {
Position position = await locationService.getCurrentLocation();
setState(() {
_currentPosition = position;
});
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GPS Location App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null)
Text(
'Latitude: ${_currentPosition?.latitude}, Longitude: ${_currentPosition?.longitude}'),
SizedBox(height: 20),
ElevatedButton(
onPressed: _getCurrentLocation,
child: Text('Get Current Location'),
),
],
),
),
);
}
}
LocationService.dart
import 'package:geolocator/geolocator.dart';
class LocationService {
Future<Position> getCurrentLocation() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled, don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}
}




10. To writes data to the SD Card

Add the line <uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in the AndroidManifest.xml file, within the <manifest> tag, just after the
</application> tag.
Add the lines permission_handler: ^11.3.1 under the cupertino_icons section in the
pubspec.yaml file.


Main.dart


import 'package:flutter/material.dart';
import 'package:practicals/SDCardWriteScreen/SDCardWriteScreen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter SDCard Demo',
home: SDCardWriteScreen(),
);
}
}
SDCardWriteScreen.dart
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:io';
class SDCardWriteScreen extends StatefulWidget {
const SDCardWriteScreen({super.key});
@override
State<SDCardWriteScreen> createState() => _SDCardWriteScreenState();
}
class _SDCardWriteScreenState extends State<SDCardWriteScreen> {
Future<void> _requestPermissions() async {
await Permission.storage.request();
}
Future<void> _writeData() async {
await _requestPermissions();
const directoryPath = "/storage/emulated/0/Download/DEMO";
final directory = Directory(directoryPath);
if (!await directory.exists()) {
await directory.create(recursive: true);
}
File file = File('$directoryPath/data.txt');
await file.writeAsString('Hello, SD Card!');
mounted
? ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
backgroundColor: Colors.green,
content: Text("File is successfully write to SD Card")))
: null;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SD Card Writer'),
),
body: Center(
child: ElevatedButton(
onPressed: _writeData,
child: Text('Write to SD Card'),
),
),
);
}
}




11. To create an alart

import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Alert Demo',
home: AlertScreen(),
);
}
}
class AlertScreen extends StatefulWidget {
const AlertScreen({super.key});
@override
State<AlertScreen> createState() => _AlertScreenState();
}
class _AlertScreenState extends State<AlertScreen> {
void _showMessageAlert(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text("New Message"),
content: Text("Hello, this is a new message!"),
actions: <Widget>[
TextButton(
child: Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Message Alert App'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_showMessageAlert(context);
},
child: Text('Receive Message'),
),
),
);
}
}

12. To use of RSS feed.

Add the lines http: ^1.2.0 and xml: ^6.5.0 under the cupertino_icons section in
the pubspec.yaml file.
Add the line
<uses-permission android:name="android.permission.INTERNET" />
in the AndroidManifest.xml file, within the <manifest> tag, just after the
</application> tag.


import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:xml/xml.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter RSS Demo',
home: RssScreen(),
);
}
}

Future<List<dynamic>> fetchRssFeed() async {
final response = await http.get(
Uri.parse("https://developer.apple.com/news/releases/rss/releases.rss"));
if (response.statusCode == 200) {
final document = XmlDocument.parse(response.body);
final items = document.findAllElements('item');
return items.map((item) => _parseItem(item)).toList();
} else {
throw Exception('Failed to load RSS feed');
}
}
Map<String, String> _parseItem(XmlElement item) {
final title = item.findElements('title').first.innerText;
final link = item.findElements('link').first.innerText;
final pubDate = item.findElements('pubDate').first.innerText;
return {'title': title, 'link': link, 'pubDate': pubDate};
}
class RssScreen extends StatefulWidget {
const RssScreen({super.key});
@override
State<RssScreen> createState() => _RssScreenState();
}
class _RssScreenState extends State<RssScreen> {
Future<List<dynamic>>? _futureFeed;
@override
void initState() {
super.initState();
_futureFeed = fetchRssFeed();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Apple Developer News - RSS'),
),
body: Center(
child: FutureBuilder(
future: _futureFeed,
builder: (context, snapshot) {
if (snapshot.hasData) {
final items = snapshot.data as List<dynamic>;
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
title: Text(item['title']),
subtitle: Text(item['pubDate']),
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return CircularProgressIndicator();
},
),
),
);
}
}


13. To send an email

Add the lines url_launcher: ^6.3.0 under the cupertino_icons section in the
pubspec.yaml file.

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Email Demo',
home: SendEmailScreen(),
);
}
}

class SendEmailScreen extends StatefulWidget {
const SendEmailScreen({super.key});
@override
State<SendEmailScreen> createState() => _SendEmailScreenState();
}
class _SendEmailScreenState extends State<SendEmailScreen> {
final _emailController = TextEditingController();
final _subjectController = TextEditingController();
final _bodyController = TextEditingController();
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Email Sender'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
controller: _emailController,
decoration: const InputDecoration(labelText: 'Email Address'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter an email address';
}
// Basic email validation
if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
},
),
TextFormField(
controller: _subjectController,
decoration: const InputDecoration(labelText: 'Subject'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter a subject';
}
return null;
},
),
TextFormField(
controller: _bodyController,
decoration: const InputDecoration(labelText: 'Body'),
maxLines: 4,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter the body of the email';
}
return null;
},
),
const SizedBox(height: 20),
ElevatedButton(
onPressed: _sendEmail,
child: const Text('Send Email'),
),
],
),
),
),
);
}
void _sendEmail() async {
if (_formKey.currentState!.validate()) {
final Uri emailLaunchUri = Uri(
scheme: 'mailto',
path: _emailController.text,
query: encodeQueryParameters(<String, String>{
'subject': _subjectController.text,
'body': _bodyController.text,
}),
);
try {
await launchUrl(emailLaunchUri);
} catch (e) {
print('Could not launch $emailLaunchUri');
}
}
}
String? encodeQueryParameters(Map<String, String> params) {
return params.entries
.map((MapEntry<String, String> e) =>
'${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
.join('&');
}
}



14. To create game application

Add the lines flame: ^1.0.0 under the cupertino_icons section in the pubspec.yaml
file.


Main.dart


import 'package:flutter/material.dart';
import 'package:practicals/Game/GameScreen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Game Demo',
home: GameScreen(),
);
}
}
GameScreen.dart
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:practicals/Game/GameControllers.dart';
class GameScreen extends StatefulWidget {
const GameScreen({Key? key}) : super(key: key);
@override
_GameScreenState createState() => _GameScreenState();
}
class _GameScreenState extends State<GameScreen> {
late GameControllers game;
@override
void initState() {
super.initState();
game = GameControllers();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
alignment: Alignment.topCenter,
children: [
GameWidget(game: game),
Padding(
padding: const EdgeInsets.only(top: 50),
child: Text(
'Tap Ball Game',
style: TextStyle(color: Colors.white, fontSize: 24),
),
),
],
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
game.isStopped
? SizedBox()
: CircleAvatar(
radius: 30,
backgroundColor: Colors.blue,
child: IconButton(
onPressed: () {
setState(() {
if (game.isPaused) {
game.resumeGame();
} else {
game.pauseGame();
}
});
},
icon: Icon(game.isPaused ? Icons.not_started : Icons.pause),
),
),
SizedBox(height: 10),
CircleAvatar(
radius: 30,
backgroundColor: Colors.blue,
child: IconButton(
onPressed: () {
setState(() {
if (game.isStopped) {
game.startGame();
} else {
game.resumeGame();
game.stopGame();
}
});
},
icon: Icon(game.isStopped ? Icons.play_arrow : Icons.stop),
),
),
],
),
);
}
}
GameControllers.dart
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flutter/material.dart';
class GameControllers extends FlameGame with TapDetector {
late SpriteComponent box;
int score = 0;
bool isPaused = false;
bool isStopped = false;
@override
Future<void> onLoad() async {
await super.onLoad();
box = SpriteComponent()
..sprite = await loadSprite('ball.png')
..size = Vector2(100, 100)
..position = Vector2(size.x / 2 - 50, size.y / 2 - 50);
add(box);
}
@override
void onTapDown(TapDownInfo info) {
if (isPaused || isStopped) return;
super.onTapDown(info);
if (box.containsPoint(info.eventPosition.global)) {
score++;
print('Score: $score');
}
}
@override
void update(double dt) {
if (isPaused || isStopped) return;
super.update(dt);
box.position.add(Vector2(100 * dt, 0));
if (box.position.x > size.x) {
box.position.x = 0;
}
}
@override
void render(Canvas canvas) {
super.render(canvas);
final textPainter = TextPainter(
text: TextSpan(
text: 'Score: $score',
style: TextStyle(color: Colors.white, fontSize: 20),
),
textDirection: TextDirection.ltr,
);
textPainter.layout();
textPainter.paint(canvas, const Offset(20, 100));
}
void pauseGame() {
isPaused = true;
pauseEngine();
}
void resumeGame() {
isPaused = false;
resumeEngine();
}
void stopGame() {
isStopped = true;
pauseEngine();
score = 0;
}
void startGame() {
isStopped = false;
resumeEngine();
}
}


15. To create alarm clock

Add the lines flutter_alarm_clock: ^0.1.1 under the cupertino_icons section in the
pubspec.yaml file.
import 'package:flutter/material.dart';
import 'package:flutter_alarm_clock/flutter_alarm_clock.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Alarm Demo',
home: AlarmScreen(),
);
}
}
class AlarmScreen extends StatefulWidget {
const AlarmScreen({Key? key}) : super(key: key);
@override
State<AlarmScreen> createState() => _AlarmScreenState();
}
class _AlarmScreenState extends State<AlarmScreen> {
TimeOfDay _time = TimeOfDay.now();
void _setAlarm(BuildContext context) async {
TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: _time,
);
if (picked != null && picked != _time) {
setState(() {
_time = picked;
});
FlutterAlarmClock.createAlarm(hour: _time.hour, minutes: _time.minute);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Alarm Clock'),
),
body: Center(
child: Column(
children: <Widget>[
Container(
margin: const EdgeInsets.all(25),
child: TextButton(
child: const Text(
'Create alarm',
style: TextStyle(fontSize: 20),
),
onPressed: () async {
_setAlarm(context);
},
),
),
Container(
margin: const EdgeInsets.all(25),
child: const TextButton(
onPressed: FlutterAlarmClock.showAlarms,
child: Text(
'Show alarms',
style: TextStyle(fontSize: 20),
),
),
),
],
),
),
);
}
}

Comments