Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return Future value

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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(...);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading