Home > Back-end >  Flutter make changing app language persistent while using Provider
Flutter make changing app language persistent while using Provider

Time:04-13

I have a working example of the ability for the user to change the language using provider and is working fine, but when I close the app and come back it goes back to the default one 'en', I just want to have the latest one chosen by the user and if the user didn't choose any other one than just leave it to the default value.

// main.dart

@override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => LocaleProvider()),
      ],
      child: Consumer<LocaleProvider>(
        builder: (context, provider, snapshot) {
          return MaterialApp(
            debugShowCheckedModeBanner: false,
            locale: provider.locale,
            home: screenToShow,
            supportedLocales: L10n.all,
            localizationsDelegates: const [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
            ],
          );
        },
      ),
    );
  }


class LocaleProvider with ChangeNotifier {
  Locale? _locale;

  Locale? get locale => _locale;

  void setLocale(Locale locale) {
    if (!L10n.all.contains(locale)) return;
    _locale = locale;
    notifyListeners();
  }
}

// dropdown to change language

Consumer<LocaleProvider>(
                    builder: (context, provider, snapshot) {
                      var lang =
                          provider.locale ?? Localizations.localeOf(context);
                      return DropdownButton(
                        value: lang,
                        onChanged: (Locale? val) {
                          provider.setLocale(val!);
                        },
                        items: L10n.all
                            .map(
                              (e) => DropdownMenuItem(
                                value: e,
                                child: _title(e.languageCode),
                              ),
                            )
                            .toList(),
                      );
                    },
                  )

CodePudding user response:

Use Shared Preference (https://pub.dev/packages/shared_preferences).

  1. Store Language Code in Shared Preference in setLocale(Locale locale) Method.

  2. Now make another method to get Language Code from Shared Preference. convert that string to Locale. and set that local to provider so that your consumers gets updated Locale when app restarts. Call this method in initState of your main widget.

  • Related