Skip to content

Commit

Permalink
Fix preferences initialization error
Browse files Browse the repository at this point in the history
  • Loading branch information
problematicconsumer committed Dec 21, 2023
1 parent 249955e commit 6b67ae6
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
15 changes: 11 additions & 4 deletions lib/bootstrap.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,6 @@ Future<void> lazyBootstrap(
final appInfo = await container.read(appInfoProvider.future);

await container.read(sharedPreferencesProvider.future);
await PreferencesMigration(
sharedPreferences: container.read(sharedPreferencesProvider).requireValue,
).migrate();

final enableAnalytics = container.read(enableAnalyticsProvider);

await SentryFlutter.init(
Expand Down Expand Up @@ -89,6 +85,17 @@ Future<void> _lazyBootstrap(
ProviderContainer container,
Environment env,
) async {
try {
await PreferencesMigration(
sharedPreferences: container.read(sharedPreferencesProvider).requireValue,
).migrate();
} catch (e) {
_logger.error("preferences migration failed", e);
if (env == Environment.dev) rethrow;
_logger.info("clearing preferences");
await container.read(sharedPreferencesProvider).requireValue.clear();
}

final debug = container.read(debugModeNotifierProvider) || kDebugMode;

final filesEditor = container.read(filesEditorServiceProvider);
Expand Down
29 changes: 27 additions & 2 deletions lib/core/preferences/preferences_provider.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
import 'dart:io';

import 'package:loggy/loggy.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared_preferences/shared_preferences.dart';

part 'preferences_provider.g.dart';

@Riverpod(keepAlive: true)
Future<SharedPreferences> sharedPreferences(SharedPreferencesRef ref) async =>
SharedPreferences.getInstance();
Future<SharedPreferences> sharedPreferences(SharedPreferencesRef ref) async {
final logger = Loggy("preferences");
SharedPreferences? sharedPreferences;

logger.debug("initializing preferences");
try {
sharedPreferences = await SharedPreferences.getInstance();
} catch (e) {
logger.error("error initializing preferences", e);
if (!Platform.isWindows && !Platform.isLinux) {
rethrow;
}
// https://github.com/flutter/flutter/issues/89211
final directory = await getApplicationSupportDirectory();
final file = File(p.join(directory.path, 'shared_preferences.json'));
if (file.existsSync()) {
file.deleteSync();
}
}

return sharedPreferences ??= await SharedPreferences.getInstance();
}

0 comments on commit 6b67ae6

Please sign in to comment.