mc_gallery/lib/features/core/services/overlay_service.dart

60 lines
1.8 KiB
Dart
Raw Normal View History

2022-12-20 08:47:07 +00:00
import 'package:flutter/widgets.dart';
2022-12-25 21:17:59 +00:00
import '/locator.dart';
import 'logging_service.dart';
2022-12-20 08:47:07 +00:00
class OverlayService {
2022-12-22 11:17:08 +00:00
OverlayService({
2022-12-20 08:47:07 +00:00
required LoggingService loggingService,
}) : _loggingService = loggingService;
final LoggingService _loggingService;
2022-12-22 11:17:08 +00:00
final Map<int, OverlayEntry> _overlayEntryMap = {};
2022-12-20 08:47:07 +00:00
2022-12-22 11:17:08 +00:00
void insertOverlayEntry(
BuildContext context, {
required String tag,
2022-12-20 08:47:07 +00:00
required OverlayEntry overlayEntry,
2022-12-22 11:17:08 +00:00
}) {
2022-12-22 21:29:37 +00:00
if (!_overlayEntryMap.containsKey(tag.hashCode) && !overlayEntry.mounted) {
_overlayEntryMap.addEntries([MapEntry(tag.hashCode, overlayEntry)]);
try {
Overlay.of(context, rootOverlay: true)?.insert(overlayEntry);
//todo(mehul): Fix and not ignore Overlay building while Widget building error.
} on FlutterError catch (_) {}
_loggingService.info('Overlay inserted with tag: $tag');
2023-01-01 12:04:22 +00:00
} else {
2022-12-22 21:29:37 +00:00
_loggingService.info('Overlay with tag: $tag, NOT inserted');
2023-01-01 12:04:22 +00:00
}
2022-12-22 11:17:08 +00:00
}
void removeOverlayEntry({
required String tag,
}) {
2022-12-22 21:29:37 +00:00
if (_overlayEntryMap.containsKey(tag.hashCode)) {
final _overlayEntry = _overlayEntryMap[tag.hashCode];
if (_overlayEntry?.mounted ?? false) {
_overlayEntryMap[tag.hashCode]?.remove();
_overlayEntryMap.remove(tag.hashCode);
_loggingService.info('Overlay removed with tag: $tag');
2023-01-01 12:04:22 +00:00
} else {
2022-12-22 21:29:37 +00:00
_loggingService.info('Overlay with tag: $tag already mounted OR not found. Skipped');
2023-01-01 12:04:22 +00:00
}
} else {
2022-12-22 21:29:37 +00:00
_loggingService.info('Overlay with tag: $tag already exists. Skipped');
2023-01-01 12:04:22 +00:00
}
2022-12-20 08:47:07 +00:00
}
void dispose() {
for (final overlayEntry in _overlayEntryMap.values) {
if (overlayEntry.mounted) {
overlayEntry.remove();
}
}
_overlayEntryMap.clear();
}
static OverlayService get locate => Locator.locate();
}