From 6b67ae6da3a10b3ba02df40bceb15ca5d87991f2 Mon Sep 17 00:00:00 2001 From: problematicconsumer Date: Thu, 21 Dec 2023 16:57:58 +0330 Subject: [PATCH] Fix preferences initialization error --- lib/bootstrap.dart | 15 +++++++--- .../preferences/preferences_provider.dart | 29 +++++++++++++++++-- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/lib/bootstrap.dart b/lib/bootstrap.dart index 1d4678d8e..5278b8740 100644 --- a/lib/bootstrap.dart +++ b/lib/bootstrap.dart @@ -50,10 +50,6 @@ Future 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 _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); diff --git a/lib/core/preferences/preferences_provider.dart b/lib/core/preferences/preferences_provider.dart index 533f6bd8b..830d18228 100644 --- a/lib/core/preferences/preferences_provider.dart +++ b/lib/core/preferences/preferences_provider.dart @@ -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(SharedPreferencesRef ref) async => - SharedPreferences.getInstance(); +Future 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(); +}