Reputation: 83
I am developing an app with Flutter in which the user preferences affect the UI, for instance the user preferred metric system affects how measure are shown by converting to kg or lbs.
I was curious on how you would implement a retrieval method for the user preferences in a way that:
I am using Riverpod and the closest solution that came to my mind is to use a Stream to get the User Preferences and watch it in the main, above the MaterialApp Widget, so that I can access the UserPreferences value as below.
Main:
class MyApp extends ConsumerWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
return _UserEagerInitialization(
child: MaterialApp.router(
locale: context.locale,
builder: (context, widget) =>
responsiveAppBuilder.defineDevicesScreenWidth(widget!),
debugShowCheckedModeBanner: false,
title: 'App',
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
theme: AppTheme.themeData,
routerConfig: router,
));
}
}
class _UserEagerInitialization extends ConsumerWidget {
const _UserEagerInitialization({required this.child});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final userAuthenticationStream =
ref.watch(getUserAuthenticationStatusProvider);
final userPreferencesStream = ref.watch(getUserPreferencesProvider);
final userProfileStream = ref.watch(getUserProfileProvider);
return userAuthenticationStream.maybeWhen(
data: (userSession) => userPreferencesStream.maybeWhen(
data: (userPreferences) => userProfileStream.maybeWhen(
data: (userProfile) => child,
orElse: () => const LoadingSpinner(),
skipLoadingOnRefresh: true,
skipLoadingOnReload: true),
orElse: () => const LoadingSpinner(),
skipLoadingOnRefresh: true,
skipLoadingOnReload: true),
orElse: () => const LoadingSpinner(),
skipLoadingOnRefresh: true,
skipLoadingOnReload: true);
}
}
Accessing User Preferences synchrounously somewhere else:
ref.watch(getUserPreferencesProvider).requireValue
Why do I want to change?
Documentation used for the above approach: https://riverpod.dev/docs/essentials/eager_initialization
Upvotes: 0
Views: 296
Reputation: 46
Maybe take a look at this tutorial: https://docs.flutter.dev/cookbook/persistence/key-value
It is a tutorial from flutter that uses the shared_preferences package. It is only usable if you store small values (it was made for small preferences), and may remove the need to store these values in your database, but if you want to track those preferences with your database, this is not what you need. In this case, maybe a splash screen could do the trick ?
Upvotes: -1