0

I'm trying to use SharedPreferences to store persistently locale value. My code looks like this:

  Locale locale = const Locale('en');

  Locale getLocale(){
    _sharedPreferencesServices.read('locale', String).then((value) {
      locale = Locale(value ?? 'en');
    });
    return locale;
  }

Is it possible to return locale value after it is assigned inside then function? I want to get locale to use it in following function:

class MyApp extends ConsumerWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context,WidgetRef ref) {
    return MaterialApp(
      title: 'CarAlgo',
      locale: ref.watch(localeProvider).getLocale(),
      localizationsDelegates: const [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: S.delegate.supportedLocales,
      navigatorKey: navigatorKey,
      scaffoldMessengerKey: scaffoldMessengerKey,
      theme: AppTheme().theme1,
      home: const MainPage(),
    );
  }
}
  • what keeps you from doing exactly that? instead of `Locale getLocale` why not simply write Future getLocale() and return the future? – adnan_e Feb 15 '22 at 10:37
  • I want to use it in the MaterialApp as following: return MaterialApp( title: 'CarAlgo', locale: ref.watch(localeProvider).getLocale(), localizationsDelegates: const [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: S.delegate.supportedLocales, navigatorKey: navigatorKey, scaffoldMessengerKey: scaffoldMessengerKey, theme: AppTheme().theme1, home: const MainPage(), ); – Julian Modlinski Feb 15 '22 at 10:38
  • Expand your question with these information and more, if possible, because it's not really clear where the problem is. If you need the value returned by the `read`, why don't you just put an `await` before it (like `var locale = await _sharedPrefs.read(...);` and make the `getLocale` an `async` method? – il_boga Feb 15 '22 at 10:47

1 Answers1

2

Example 1

  Future<Locale> getLocale(){
    return _sharedPreferencesServices.read('locale', String).then((value) {
      return Locale(value ?? 'en');
    });
  }

Example 2

  Future<Locale> getLocale() async {
    var value = await _sharedPreferencesServices.read('locale', String);
    return Locale(value ?? 'en');
  }

However, reading your comment, your problem isn't how to properly write this function, but how to call this function inside the main method.

You can make it async (But also see this).

void main() async {
   var locale = await <...>.getLocale();
   return MaterialApp(...);
}
adnan_e
  • 1,764
  • 2
  • 16
  • 25