live_activity_update 0.0.5
live_activity_update: ^0.0.5 copied to clipboard
Live Activity Update Plugin
example/lib/main.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:live_activity_update/live_activity_update.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String? _activityId;
bool _isActivityRunning = false;
double _currentProgress = 0.0;
final _liveActivityUpdatePlugin = LiveActivityUpdate();
final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
@override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
String platformVersion;
try {
platformVersion =
await _liveActivityUpdatePlugin.getPlatformVersion() ?? 'Unknown platform version';
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
Future<void> _startSleepMode() async {
try {
final id = await _liveActivityUpdatePlugin.start(data: {
'title': 'Sleep Mode Active',
'remaining': '8:00:00',
'progress': 0.0,
'progressPercent': '0.0%',
});
setState(() {
_activityId = id;
_isActivityRunning = true;
_currentProgress = 0.0;
});
_showSnackBar('Sleep Mode Started: $id');
} on LiveActivityException catch (e) {
_showSnackBar('Error: ${e.code} - ${e.message}');
} catch (e) {
_showSnackBar('Failed to start sleep mode: $e');
}
}
Future<void> _updateSleepMode() async {
if (_activityId == null) return;
try {
// Simulate progress update
final newProgress = (_currentProgress + 0.125).clamp(0.0, 1.0); // 8 steps to complete
// Calculate remaining time (assuming 8 hours total)
final totalMinutes = 480; // 8 hours = 480 minutes
final remainingMinutes = (totalMinutes * (1.0 - newProgress)).round();
final remaining = _formatSleepTime(Duration(minutes: remainingMinutes));
final progressPercent = '${(newProgress * 100).toStringAsFixed(1)}%';
String status;
if (newProgress >= 1.0) {
status = 'Sleep Complete';
} else if (newProgress >= 0.75) {
status = 'Deep Sleep Phase';
} else if (newProgress >= 0.5) {
status = 'REM Sleep Phase';
} else if (newProgress >= 0.25) {
status = 'Light Sleep Phase';
} else {
status = 'Sleep Mode Active';
}
await _liveActivityUpdatePlugin.update(
id: _activityId!,
data: {
'title': status,
'remaining': remaining,
'progress': newProgress,
'progressPercent': progressPercent,
},
);
setState(() {
_currentProgress = newProgress;
});
_showSnackBar('Sleep Mode Updated - $progressPercent complete');
} on LiveActivityException catch (e) {
_showSnackBar('Update Error: ${e.code} - ${e.message}');
} catch (e) {
_showSnackBar('Failed to update sleep mode: $e');
}
}
Future<void> _stopSleepMode() async {
if (_activityId == null) return;
try {
await _liveActivityUpdatePlugin.stop(id: _activityId!);
setState(() {
_activityId = null;
_isActivityRunning = false;
_currentProgress = 0.0;
});
_showSnackBar('Sleep Mode Stopped');
} on LiveActivityException catch (e) {
_showSnackBar('Stop Error: ${e.code} - ${e.message}');
} catch (e) {
_showSnackBar('Failed to stop sleep mode: $e');
}
}
String _formatSleepTime(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, "0");
String hours = twoDigits(duration.inHours);
String minutes = twoDigits(duration.inMinutes.remainder(60));
String seconds = twoDigits(duration.inSeconds.remainder(60));
return "$hours:$minutes:$seconds";
}
void _showSnackBar(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
duration: const Duration(seconds: 3),
),
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sleep Mode Live Activity Demo',
scaffoldMessengerKey: _scaffoldMessengerKey,
theme: ThemeData(
primarySwatch: Colors.indigo,
useMaterial3: true,
),
home: Scaffold(
backgroundColor: const Color(0xFF1A237E),
appBar: AppBar(
title: const Text('Sleep Mode Demo', style: TextStyle(color: Colors.white)),
backgroundColor: const Color(0xFF1A237E),
elevation: 0,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Card(
color: Colors.white.withOpacity(0.1),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.bedtime, color: Colors.white, size: 24),
const SizedBox(width: 8),
Text(
'Sleep Mode Active',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
const SizedBox(height: 12),
if (_isActivityRunning) ...[
Text(
'Time remaining: ${_formatSleepTime(Duration(minutes: (480 * (1.0 - _currentProgress)).round()))}',
style: TextStyle(
fontSize: 14,
color: Colors.white.withOpacity(0.9),
),
),
const SizedBox(height: 12),
LinearProgressIndicator(
value: _currentProgress,
backgroundColor: Colors.white.withOpacity(0.3),
valueColor: const AlwaysStoppedAnimation<Color>(Colors.white),
),
const SizedBox(height: 8),
Text(
'${(_currentProgress * 100).toStringAsFixed(1)}% complete',
style: TextStyle(
fontSize: 12,
color: Colors.white.withOpacity(0.8),
),
),
] else ...[
Text(
'Status: Inactive',
style: TextStyle(
fontSize: 14,
color: Colors.white.withOpacity(0.9),
),
),
],
],
),
),
),
const SizedBox(height: 20),
Card(
color: Colors.white.withOpacity(0.1),
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Platform Information',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
const SizedBox(height: 8),
Text(
'Running on: $_platformVersion',
style: TextStyle(color: Colors.white.withOpacity(0.9)),
),
if (_activityId != null) ...[
const SizedBox(height: 4),
Text(
'Activity ID: $_activityId',
style: TextStyle(color: Colors.white.withOpacity(0.7)),
),
],
],
),
),
),
const SizedBox(height: 30),
ElevatedButton.icon(
onPressed: !_isActivityRunning ? _startSleepMode : null,
icon: const Icon(Icons.bedtime),
label: const Text('Start Sleep Mode'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: const Color(0xFF1A237E),
padding: const EdgeInsets.symmetric(vertical: 12),
),
),
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: _isActivityRunning && _currentProgress < 1.0
? _updateSleepMode
: null,
icon: const Icon(Icons.update),
label: const Text('Update Sleep Progress'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white.withOpacity(0.9),
foregroundColor: const Color(0xFF1A237E),
padding: const EdgeInsets.symmetric(vertical: 12),
),
),
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: _isActivityRunning ? _stopSleepMode : null,
icon: const Icon(Icons.stop),
label: const Text('Stop Sleep Mode'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
),
),
],
),
),
),
);
}
}