Mahmoud Sabri
Mahmoud Sabri

Reputation: 785

Change application locale programmatically

I need to change application locale programmatically when button pressed

my code :

MaterialApp(

          localizationsDelegates: [
            _newLocaleDelegate,
            const AppTranslationsDelegate(),
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
          ],
          supportedLocales: [
            const Locale('en', ''),
            const Locale('ar', ''),
          ],
          locale: mylocale,
          title: appTitle,
          home: Scaffold(
            body: new MyCustomForm(),

          ),
           debugShowCheckedModeBanner: false
        );

    new MaterialButton(
    onPressed: () { 
    setState(() {
        mylocale=Locale("ar","");
_newLocaleDelegate =  AppTranslationsDelegate(newLocale:mylocale);
     });
    },

     ),

translation code :

AppTranslations.of(context).text("text")

AppTranslations Class:

class AppTranslations {
  Locale locale;
  static Map<dynamic, dynamic> _localisedValues;

  AppTranslations(Locale locale) {
    this.locale = locale;
    _localisedValues = null;
  }

  static AppTranslations of(BuildContext context) {
    return Localizations.of<AppTranslations>(context, AppTranslations);
  }

  static Future<AppTranslations> load(Locale locale) async {
    AppTranslations appTranslations = AppTranslations(locale);
    String jsonContent =
    await rootBundle.loadString("assets/locale/localization_${locale.languageCode}.json");
    _localisedValues = json.decode(jsonContent);
    return appTranslations;
  }

  get currentLanguage => locale.languageCode;

  String text(String key) {
    print(key);
    if(_localisedValues!=null)
    return _localisedValues[key] ?? "$key";
    else
      return key;
  }
}

my problem :

when Locale change page direction changed without translation , to get effect translation need to refresh page or go to another page and return back,

any help

Upvotes: 0

Views: 2279

Answers (1)

Sebastian Roth
Sebastian Roth

Reputation: 11537

Could you try wrapping your MaterialApp in an AnimatedSwitcher like so:

AnimatedSwitcher(
  // Following two fields for your reference

  // duration: const Duration(milliseconds: 500),

  // transitionBuilder: (Widget child, Animation<double> animation) {
  //  return ScaleTransition(child: child, scale: animation);
  // },

  child: MaterialApp(
    // As before, the same code, however:

    key: ValueKey<Locale>(mylocale),
  ) 
) 

BTW, good practice to prefix private variables with an underscore, e.g. _myLocale.

Upvotes: 2

Related Questions