@@ -27,6 +27,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
27
27
import 'package:local_notifier/local_notifier.dart' ;
28
28
import 'package:logging/logging.dart' ;
29
29
import 'package:material_symbols_icons/symbols.dart' ;
30
+ import 'package:path/path.dart' as path;
31
+ import 'package:path_provider_linux/path_provider_linux.dart' ;
32
+ import 'package:path_provider_windows/path_provider_windows.dart' ;
30
33
import 'package:screen_retriever/screen_retriever.dart' ;
31
34
import 'package:shared_preferences/shared_preferences.dart' ;
32
35
import 'package:window_manager/window_manager.dart' ;
@@ -125,7 +128,34 @@ Future<Widget> initialize(List<String> argv) async {
125
128
_initLogging (args);
126
129
127
130
await windowManager.ensureInitialized ();
128
- final prefs = await SharedPreferences .getInstance ();
131
+ SharedPreferences prefs;
132
+ try {
133
+ prefs = await SharedPreferences .getInstance ();
134
+ } catch (error) {
135
+ // Attempt to repair the broken preferences file
136
+ String ? directory;
137
+ if (Platform .isWindows) {
138
+ PathProviderWindows pathProvider = PathProviderWindows ();
139
+ directory = await pathProvider.getApplicationSupportPath ();
140
+ } else if (Platform .isLinux) {
141
+ PathProviderLinux pathProvider = PathProviderLinux ();
142
+ directory = await pathProvider.getApplicationSupportPath ();
143
+ }
144
+ if (directory == null ) {
145
+ throw const FormatException ('Unable to find correct directory' );
146
+ }
147
+ String appDataPath = path.join (directory, 'shared_preferences.json' );
148
+ List <int > repairedPreferences = await _repairPreferences (appDataPath);
149
+ await File (appDataPath).writeAsBytes (repairedPreferences);
150
+
151
+ try {
152
+ prefs = await SharedPreferences .getInstance ();
153
+ } catch (error) {
154
+ // Unable to repair the preferences file, therefore delete it
155
+ await File (appDataPath).delete ();
156
+ prefs = await SharedPreferences .getInstance ();
157
+ }
158
+ }
129
159
final windowManagerHelper = WindowManagerHelper .withPreferences (prefs);
130
160
final isHidden = _getIsHidden (args, prefs);
131
161
@@ -413,3 +443,13 @@ class _HelperWaiterState extends ConsumerState<_HelperWaiter> {
413
443
}
414
444
}
415
445
}
446
+
447
+ Future <List <int >> _repairPreferences (String appDataPath) async {
448
+ List <int > contents = await File (appDataPath).readAsBytes ();
449
+ var contentsGrowable = List <int >.from (contents); // Make the list growable
450
+
451
+ // Remove any NUL characters
452
+ contentsGrowable.removeWhere ((item) => item == 0 );
453
+
454
+ return contentsGrowable;
455
+ }
0 commit comments