How to manually change app language with Flutter_localizations and Bloc?

608
void main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => LanguageCubit(),
      child: BlocBuilder<LanguageCubit, Locale>(builder: (context, lang) {
        return MaterialApp(
          locale: lang,
          title: 'Localizations Sample App',
          localizationsDelegates: [
            AppLocalizations.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: [
            const Locale('en', ''), // English, no country code
            const Locale('es', ''), // Spanish, no country code
            const Locale('tr', ''),
            const Locale('it', ''),
          ],
          home: Home(),
        );
      }),
    );
  }
}

class Home extends StatelessWidget {
  //Here
  const Home({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    context.read<LanguageCubit>().changeStartLang();
    return Scaffold(
      body: Center(
        child: Container(
          color: Colors.amberAccent,
          width: 200,
          height: 200,
          child: Column(
            children: [
              Text(AppLocalizations.of(context).helloWorld),
              Divider(),
              TextButton(
                onPressed: () {
                  context.read<LanguageCubit>().changeLang(context, 'en');
                },
                child: Text('English'),
              ),
              TextButton(
                onPressed: () {
                  context.read<LanguageCubit>().changeLang(context, 'es');
                },
                child: Text('Espaniol'),
              ),
              TextButton(
                onPressed: () {
                  context.read<LanguageCubit>().changeLang(context, 'tr');
                },
                child: Text('Turkish'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class LanguageCubit extends Cubit<Locale> {
  LanguageCubit() : super(null);

  void changeStartLang() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String langCode = prefs.getString('lang');
    print(langCode);
    if (langCode != null) {
      emit(Locale(langCode, ''));
    }
  }

  void changeLang(context, String data) async {
    emit(Locale(data, ''));
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('lang', data);
  }
}

I used a method like this and it works great, simple and useful. context.read<LanguageCubit>().changeStartLang(); in build

Share:
608
Raghim Najafov
Author by

Raghim Najafov

Python,Flask,Javascript,Java,HTML,CSS

Updated on December 29, 2022

Comments

  • Raghim Najafov
    Raghim Najafov over 1 year
    void main() async {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return BlocProvider(
          create: (context) => LanguageCubit(),
          child: BlocBuilder<LanguageCubit, Locale>(builder: (context, lang) {
            return MaterialApp(
              locale: lang,
              title: 'Localizations Sample App',
              localizationsDelegates: [
                AppLocalizations.delegate,
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
              ],
              supportedLocales: [
                const Locale('en', ''), // English, no country code
                const Locale('es', ''), // Spanish, no country code
                const Locale('tr', ''),
                const Locale('it', ''),
              ],
              home: Home(),
            );
          }),
        );
      }
    }
    
    class Home extends StatelessWidget {
      const Home({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Container(
              color: Colors.amberAccent,
              width: 200,
              height: 200,
              child: Column(
                children: [
                  Text(AppLocalizations.of(context).helloWorld),
                  Divider(),
                  TextButton(
                      onPressed: () {
                        context.read<LanguageCubit>().changeLangEs(context);
                      },
                      child: Text('Change')),
                ],
              ),
            ),
          ),
        );
      }
    }
    
    class LanguageCubit extends Cubit<Locale> {
      LanguageCubit() : super(null);
    
      static final _languageEn = Locale('en', '');
      static final _languageEs = Locale('es', '');
      static final _languageTr = Locale('tr', '');
    
      void changeLangEn(context) async {
        emit(_languageEn);
      }
    
      void changeLangEs(context) async {
        emit(_languageEs);
      }
    
      void changeLangTr(context) async {
        emit(_languageTr);
      }
    }
    

    I have such an application, the problem is that when I close the application and open it, the application uses the default language again.How can I permanently change the application language to the chosen language?It would be great if an example is given through this code.Do I need to store the chosen language and then use it from that db? Does Flutter_localizations offer a simple way to do this?