Fix preferences initialization error

This commit is contained in:
problematicconsumer
2023-12-21 16:57:58 +03:30
parent 249955e1ca
commit 6b67ae6da3
2 changed files with 38 additions and 6 deletions

View File

@@ -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(
@@ -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);

View File

@@ -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();
}