fbmobile/lib/core/manager/lifecycle_manager.dart

60 lines
1.4 KiB
Dart
Raw Normal View History

2021-02-02 14:33:23 +00:00
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import '../../core/services/session_service.dart';
import '../../locator.dart';
import '../services/permission_service.dart';
2021-02-02 14:33:23 +00:00
import '../services/stoppable_service.dart';
import '../util/logger.dart';
/// Stop and start long running services
class LifeCycleManager extends StatefulWidget {
final Widget? child;
2021-02-02 14:33:23 +00:00
const LifeCycleManager({super.key, this.child});
2021-02-02 14:33:23 +00:00
2023-01-04 20:17:54 +00:00
@override
2021-02-02 14:33:23 +00:00
_LifeCycleManagerState createState() => _LifeCycleManagerState();
}
2023-01-16 00:44:34 +00:00
class _LifeCycleManagerState extends State<LifeCycleManager>
with WidgetsBindingObserver {
2021-02-02 14:33:23 +00:00
final Logger logger = getLogger();
2023-01-16 00:44:34 +00:00
List<StoppableService> servicesToManage = [
locator<SessionService>(),
locator<PermissionService>()
];
2021-02-02 14:33:23 +00:00
@override
Widget build(BuildContext context) {
return widget.child!;
2021-02-02 14:33:23 +00:00
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
2021-02-02 14:33:23 +00:00
}
@override
void dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
2021-02-02 14:33:23 +00:00
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
logger.d('LifeCycle event ${state.toString()}');
super.didChangeAppLifecycleState(state);
2023-01-04 20:17:54 +00:00
for (var service in servicesToManage) {
2021-02-02 14:33:23 +00:00
if (state == AppLifecycleState.resumed) {
service.start();
} else {
service.stop();
}
2023-01-04 20:17:54 +00:00
}
2021-02-02 14:33:23 +00:00
}
}