mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-13 17:30:28 +00:00
fix: Add mounted checks and fix memory leaks across UI components
Address potential memory leaks and state-after-dispose issues: - AppProvider: Add dispose method to clean up listeners and callbacks - MapTab: Store and restore original location callback instead of nullifying - MessagesTab: Use Timer instead of Future.delayed for highlight cleanup - ConnectionDialog: Use named listener method for proper tab controller cleanup - RoomLoginSheet: Add _isDisposed flag to handle async callback race conditions - SettingsScreen: Clear location service callbacks in dispose - Various screens: Add mounted checks before setState after async operations (contacts_tab, device_config, home_screen, map_management, packet_log, sar_template_management, sar_update_sheet, permission_request_dialog)
This commit is contained in:
@@ -51,9 +51,11 @@ class _ContactsTabState extends State<ContactsTab> {
|
||||
}
|
||||
|
||||
Future<void> _handleRefresh() async {
|
||||
if (!mounted) return;
|
||||
final appProvider = context.read<AppProvider>();
|
||||
await appProvider.refresh();
|
||||
// Also refresh location
|
||||
if (!mounted) return;
|
||||
await _getCurrentLocation();
|
||||
}
|
||||
|
||||
|
||||
@@ -347,6 +347,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
),
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
setState(() {
|
||||
_latController.text = position.latitude.toStringAsFixed(6);
|
||||
_lonController.text = position.longitude.toStringAsFixed(6);
|
||||
|
||||
@@ -279,6 +279,7 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
final appProvider = context.watch<AppProvider>();
|
||||
if (_isMapEnabled != appProvider.isMapEnabled) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
_updateTabController(appProvider.isMapEnabled);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -409,6 +409,7 @@ class _MapManagementScreenState extends State<MapManagementScreen> {
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _isLoading = false);
|
||||
_showError(AppLocalizations.of(context)!.clearCacheFailed(e.toString()));
|
||||
}
|
||||
|
||||
@@ -78,6 +78,9 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
|
||||
// MBTiles layers
|
||||
List<MapLayer> _mbtilesLayers = [];
|
||||
|
||||
// Store original location callback to restore in dispose
|
||||
void Function(Position)? _originalLocationCallback;
|
||||
|
||||
// WMS layers (Slovenian)
|
||||
late final MapLayer _slovenianAerialLayer;
|
||||
late final MapLayer _dtk25Layer;
|
||||
@@ -128,6 +131,7 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
|
||||
|
||||
// Listen to map provider for navigation requests
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return; // Check if widget is still mounted
|
||||
final mapProvider = context.read<MapProvider>();
|
||||
mapProvider.addListener(_handleMapNavigation);
|
||||
// Load WMS overlay state
|
||||
@@ -146,13 +150,13 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
|
||||
/// Note: LocationTrackingService is initialized and started by AppProvider
|
||||
/// This method only adds map-specific callbacks for rotation and UI updates
|
||||
void _setupLocationCallbacks() {
|
||||
// Store the original callback from AppProvider
|
||||
final originalCallback = _locationService.onPositionUpdate;
|
||||
// Store the original callback from AppProvider to restore in dispose
|
||||
_originalLocationCallback = _locationService.onPositionUpdate;
|
||||
|
||||
// Add map-specific callback that chains with the original
|
||||
_locationService.onPositionUpdate = (position) {
|
||||
// Call original callback first (AppProvider's logging)
|
||||
originalCallback?.call(position);
|
||||
_originalLocationCallback?.call(position);
|
||||
|
||||
// Then handle map-specific logic - early exit if not mounted or disposing
|
||||
if (!mounted || _isDisposing) {
|
||||
@@ -437,8 +441,8 @@ class _MapTabState extends State<MapTab> with AutomaticKeepAliveClientMixin {
|
||||
mapProvider.removeListener(_handleMapNavigation);
|
||||
|
||||
// DO NOT stop location tracking - it's managed by AppProvider
|
||||
// Just clear the map-specific callback
|
||||
_locationService.onPositionUpdate = null;
|
||||
// Restore the original callback instead of setting to null
|
||||
_locationService.onPositionUpdate = _originalLocationCallback;
|
||||
_mapController.dispose();
|
||||
_tileCache.dispose();
|
||||
super.dispose();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -33,6 +34,7 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
int _characterCount = 0;
|
||||
static const int _maxCharacters = 160;
|
||||
String? _highlightedMessageId;
|
||||
Timer? _highlightTimer; // Timer for clearing message highlight
|
||||
|
||||
// Message destination state
|
||||
String _destinationType =
|
||||
@@ -73,6 +75,7 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_highlightTimer?.cancel();
|
||||
_textController.dispose();
|
||||
_focusNode.dispose();
|
||||
_scrollController.dispose();
|
||||
@@ -112,8 +115,9 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
_highlightedMessageId = messageId;
|
||||
});
|
||||
|
||||
// Clear highlight after 2 seconds
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
// Clear highlight after 2 seconds using a properly managed Timer
|
||||
_highlightTimer?.cancel();
|
||||
_highlightTimer = Timer(const Duration(seconds: 2), () {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_highlightedMessageId = null;
|
||||
|
||||
@@ -73,10 +73,12 @@ class _PacketLogScreenState extends State<PacketLogScreen> {
|
||||
|
||||
// Save to temporary file
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
if (!context.mounted) return;
|
||||
final file = File('${tempDir.path}/ble_packets_${DateTime.now().millisecondsSinceEpoch}.csv');
|
||||
await file.writeAsString(buffer.toString());
|
||||
|
||||
// Share the file
|
||||
if (!context.mounted) return;
|
||||
await Share.shareXFiles(
|
||||
[XFile(file.path)],
|
||||
subject: 'MeshCore BLE Packet Logs',
|
||||
@@ -118,10 +120,12 @@ class _PacketLogScreenState extends State<PacketLogScreen> {
|
||||
|
||||
// Save to temporary file
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
if (!context.mounted) return;
|
||||
final file = File('${tempDir.path}/ble_packets_${DateTime.now().millisecondsSinceEpoch}.txt');
|
||||
await file.writeAsString(buffer.toString());
|
||||
|
||||
// Share the file
|
||||
if (!context.mounted) return;
|
||||
await Share.shareXFiles(
|
||||
[XFile(file.path)],
|
||||
subject: 'MeshCore BLE Packet Logs',
|
||||
@@ -147,27 +151,31 @@ class _PacketLogScreenState extends State<PacketLogScreen> {
|
||||
}
|
||||
|
||||
void _clearLogs(BuildContext context) {
|
||||
final parentContext = context; // Store parent context for setState
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: Text(AppLocalizations.of(context)!.clearAllData),
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: Text(AppLocalizations.of(dialogContext)!.clearAllData),
|
||||
content: const Text('Are you sure you want to clear all packet logs? This cannot be undone.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(AppLocalizations.of(context)!.cancel),
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(AppLocalizations.of(dialogContext)!.cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
widget.bleService.clearPacketLogs();
|
||||
Navigator.pop(context);
|
||||
Navigator.pop(dialogContext);
|
||||
if (!mounted) return;
|
||||
setState(() {});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Packet logs cleared')),
|
||||
);
|
||||
if (parentContext.mounted) {
|
||||
ScaffoldMessenger.of(parentContext).showSnackBar(
|
||||
const SnackBar(content: Text('Packet logs cleared')),
|
||||
);
|
||||
}
|
||||
},
|
||||
style: TextButton.styleFrom(foregroundColor: Colors.red),
|
||||
child: Text(AppLocalizations.of(context)!.clear),
|
||||
child: Text(AppLocalizations.of(dialogContext)!.clear),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -381,6 +389,7 @@ class _PacketLogScreenState extends State<PacketLogScreen> {
|
||||
// Auto-scroll to bottom
|
||||
if (_autoScroll && index == logs.length - 1) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(
|
||||
_scrollController.position.maxScrollExtent,
|
||||
|
||||
@@ -24,6 +24,7 @@ class _SarTemplateManagementScreenState extends State<SarTemplateManagementScree
|
||||
|
||||
Future<void> _initializeService() async {
|
||||
if (!_templateService.isInitialized) {
|
||||
if (!mounted) return;
|
||||
setState(() => _isLoading = true);
|
||||
await _templateService.initialize();
|
||||
if (mounted) {
|
||||
@@ -111,6 +112,7 @@ class _SarTemplateManagementScreenState extends State<SarTemplateManagementScree
|
||||
}
|
||||
|
||||
Future<void> _importFromClipboard() async {
|
||||
if (!mounted) return;
|
||||
setState(() => _isLoading = true);
|
||||
|
||||
try {
|
||||
|
||||
@@ -57,6 +57,15 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_loadRxTxPreference();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Clear location service callbacks to prevent memory leaks
|
||||
_locationService.onError = null;
|
||||
_locationService.onBroadcastSent = null;
|
||||
_locationService.onTrackingStateChanged = null;
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _loadPackageInfo() async {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
if (mounted) {
|
||||
|
||||
Reference in New Issue
Block a user