Home > Back-end >  Return Future value
Return Future value

Time:02-16

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

CodePudding user response:

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(...);
}
  • Related