4
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?

1 Answer 1

8
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

1
  • Good example!! And you also can init locale by adding create: (context) => LanguageCubit(), instead of using context.read<LanguageCubit>().changeStartLang();
    – Kin Cheng
    Dec 8, 2022 at 3:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.