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
informationAdd 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'),
),
),
);
}
}
Comments
Post a Comment