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