Home > database >  My app's language is not changing using a button in Flutter
My app's language is not changing using a button in Flutter

Time:03-15

I am trying to change my app's language in Flutter using UI in real time. I want, that as soon as someone taps on the options, language of app should change. For that, I was following documentation - Flutter's Documentation for changing language

I defined my material app like this -

ValueNotifier<Locale> locale = ValueNotifier(Locale("en"));

return const MaterialApp(
  title: 'Test App',
  localizationsDelegates: [
    AppLocalizations.delegate, 
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: L10n.all,
  locale: locale.value, 
  home: LanguageSelectionScreen(),
  localeResolutionCallback: (locale, supportedLocales) {
          if(defaultLanguage!=null) {
            Intl.defaultLocale = defaultLanguage?.toLanguageTag();
            return defaultLanguage;
          }
          if(locale==null) {
            Intl.defaultLocale = supportedLocales.first.toLanguageTag();
            return supportedLocales.first;
          }
          for (var supportedLocale in supportedLocales) {
            if (supportedLocale.languageCode == locale.languageCode) {
              Intl.defaultLocale = supportedLocale.toLanguageTag();
              return supportedLocale;
            }
          }
          Intl.defaultLocale = supportedLocales.first.toLanguageTag();
          return supportedLocales.first;
        },
);

I defined L10 as-

class L10n {
  static final all = [
    const Locale('en'),
    const Locale('gu'),
    const Locale('hi'),
    const Locale('bn'),
    const Locale('pa'),
  ];
}

This is app_gu.arb -

{
  "language": "ગુજરાતી",
  "helloWorld": "હેલો વર્લ્ડ"
}

And app_en.arb -

{
  "language": "English",
  "@language": {
    "description" : "The current language"
  },
  "helloWorld": "Hello World",
  "@helloWorld": {
    "description" : "A programmer greeting"
  }
}

app_localizations_gu.dart -

import 'app_localizations.dart';

/// The translations for Gujarati (`gu`).
class AppLocalizationsGu extends AppLocalizations {
  AppLocalizationsGu([String locale = 'gu']) : super(locale);

  @override
  String get language => 'ગુજરાતી';

  @override
  String get helloWorld => 'હેલો વર્લ્ડ';
}

Now, I wanted to change language using a button, I used these functions -
void setLocale(Locale value) { setState(() { locale.value = value; }); }

  setLanguage(String code) {
    setLocale(Locale.fromSubtags(languageCode: code));
  }

And I want to test my code here -

                   InkWell(
                      onTap: () {
                        setLanguage("gu");
                      },
                        child: LanguageTile(shortForm: "GU", fullName: "Gujarati", isSelected: false,),
                    ),
                    LanguageTile(shortForm: "A", fullName: "English", isSelected: false,),
                    LanguageTile(shortForm: "HIN", fullName: "Hindi", isSelected: true,),
                    LanguageTile(shortForm: "PA", fullName: "Punjabi", isSelected: false,),
                    ValueListenableBuilder(
                       valueListenable: locale,
                       builder: (BuildContext context, Locale l, Widget? child) {
                         return Text(AppLocalizations.of(context)!.helloWorld);
                  },
                ),

But it is not changing when I am tapping on my Button. Can somepne please tell me what is the correction needed for this?

And also, I have a lot of code in writing, so, is there any way that I don't have to hardcode everything that I want to change, instead it automatically gets updated? Please do tell me.

CodePudding user response:

https://youtu.be/Zw4KoorVxgg

Here's an good video tutorial.

I am using this method.

If you have any doubts feel free to ask.

CodePudding user response:

you can see this for the reference that what are the supported values(locales) and how to initialize localizations delegate.

child: GetMaterialApp(

      initialBinding: MainBindings(),

      debugShowCheckedModeBanner: false,

      initialRoute: Routes.INITIAL,

      getPages: AppPages.pages,

      localizationsDelegates: [

        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],

      supportedLocales: [
        const Locale('en', ''), // English, no country code
        const Locale('id', ''), // Spanish, no country code
      ],
      // home: AddBeneficiaryScreen(customerProfile: CustomerProfile(firstName: "Safiya",mobileNumber: "7013601812"),isNewUser: true,),
      title: "xyz",
      theme: themeData),

child: InternationalPhoneNumberInput(
                                countries: ['ID', 'SG', 'IN'],
                                onInputChanged: (PhoneNumber number) {
                                  print(number.phoneNumber);
                                  controller.errorMessage.value = "";
                                  controller.mobileNumber.value =
                                      number.phoneNumber;
                                },
                                onInputValidated: (bool value) {
                                  print(value);
                                },
                                selectorConfig: SelectorConfig(
                                  selectorType:
                                  PhoneInputSelectorType.DROPDOWN,
                                ),
                                ignoreBlank: false,
                                selectorTextStyle:
                                TextStyle(color: Colors.black),
                                initialValue: number,
                                textFieldController: controller
                                    .mobileNumberTextEditController,
                                inputBorder: InputBorder.none,
                                inputDecoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintText: getTranslation(
                                      Strings.PHONE_NUMBER),
                                ),
                              ),

i am giving this code for the reference that in this code,i am trying to change the locale using the dropdown and it is possible through the selected config and the onInputChanged function.i.e showing the drop down of 3 numbers,indonesian,indian, numbers etc.

  • Related