Home>

How to switch the locale programmatically? When you click on the buttons, the locale should change, but it does not change. Below is the full code and screenshot.

intl_en.arb

{
 "str1" : "Name Page",
 "str2" : "english",
 "str3" : "english",
 "str4" : "Hello World!"
}

intl_ru.arb

{
 "str1" : "Page Name",
 "str2" : "english",
 "str3" : "Russian",
 "str4" : "Hello World!"
}

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';
void main()=> runApp(const MyApp());
Locale _locale= const Locale('en', '');
void funEn() {
 _locale= const Locale('en', '');
}
void funRu() {
 _locale= const Locale('ru', '');
}
class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);
 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   localizationsDelegates: const[
    s.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
   ],
   supportedLocales:const[
    Locale('en', ''), //English
    Locale('ru', ''), //English
   ],
   //setting the locale for the application
   locale: _locale,
   debugShowCheckedModeBanner: false,
   title: 'Name App',
   theme: ThemeData(
    primarySwatch: Colors.blue,
   ),
   home: const MyHomePage(),
  );
 }
}
class MyHomePage extends StatefulWidget {
 const MyHomePage({Key? key}) : super(key: key);
 @override
 _MyHomePageState createState()=> _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
 @override
 void initState() {
  super.initState();
 }
 @override
 void dispose() {
  superdispose();
 }
 @override
 Widget build(BuildContext context) {
  return Scaffold(
   appBar: AppBar(
    title: Text(S.of(context).str1),
   ),
   body: SafeArea(
    child: Column(
     mainAxisSize: MainAxisSize.max,
     children:[
      Padding(
       padding: const EdgeInsets.symmetric(vertical: 16.0),
       child:Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children:[
         TextButton(
          onPressed: () {
           setState(() {
            funEn();
           });
          },
          child: Text(S.of(context).str2),
          style:ButtonStyle(
           alignment: Alignment.center,
           minimumSize: MaterialStateProperty.all(const Size(128, 36)),
           foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
           backgroundColor: MaterialStateProperty.all(Colors.grey.shade200),
           padding: MaterialStateProperty.all(EdgeInsets.zero),
           textStyle: MaterialStateProperty.all(const TextStyle(fontSize: 20)),
           side: MaterialStateProperty.all(
            const BorderSide(
             color: Colors.red,
             width: 1.0
            )
           ),
           shape: MaterialStateProperty.all(
            const RoundedRectangleBorder(
             borderRadius: BorderRadius.all(Radius.circular(5.0)),
            )
           ),
          ),
         ),
         TextButton(
          onPressed: () {
           setState(() {
            funRu();
           });
          },
          child: Text(S.of(context).str3),
          style:ButtonStyle(
           alignment: Alignment.center,
           minimumSize: MaterialStateProperty.all(const Size(128, 36)),
           foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
           backgroundColor: MaterialStateProperty.all(Colors.grey.shade200),
           padding: MaterialStateProperty.all(EdgeInsets.zero),
           textStyle: MaterialStateProperty.all(const TextStyle(fontSize: 20)),
           side: MaterialStateProperty.all(
            const BorderSide(
             color: Colors.red,
             width: 1.0
            )
           ),shape: MaterialStateProperty.all( const RoundedRectangleBorder(
             borderRadius: BorderRadius.all(Radius.circular(5.0)),
            )
           ),
          ),
         ),
        ]
       ),
      ),
      Expanded(
       flex: 1
       child: Center(
        child: Text(
         S.of(context).str4,
         style:const TextStyle(
          fontSize: 36.0
          color: Colors.pink
         ),
        ),
       ),
      ),
     ]
    ),
   ),
  );
 }
}
  • Answer # 1

    You're calling setState in the wrong place.

    Here's an example of how you can do it:

    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState()=> _MyAppState();
      static void ofLocale(BuildContext context, Locale locale)=> context.findAncestorStateOfType<_MyAppState>().setLocale(locale);
    }
    class _MyAppState extends State<MyApp> {
      locale_locale;
      void setLocale(Locale value) {
        setState(() {
          _locale= value;
        });
      }
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          locale: _locale,
          localizationsDelegates: const[
            s.delegate,
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales:const[
            Locale('en', ''), //English
            Locale('ru', ''), //Russian
          ],
          debugShowCheckedModeBanner: false,
          title: 'Name App',
          theme: ThemeData(
           primarySwatch: Colors.blue,
          ),
          home: const MyHomePage(),
        );
      }
    }
    ...
    MyApp.ofLocale(context, Locale('en', ''));