Is it possible to listen for system language change in Flutter?

Viewed 477

Is it possible to listen when the user changes their system language? I need to clear some list when the user changes their language. Now I am detecting the language in the void main() function on startup.


void main() async {
  // Firebase Push Notifications initialization
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(backgroundHandler);
  detectLanguageChange();
  WidgetsBinding.instance.addObserver(this);


  runApp(const MyApp());
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
 @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
  }

  @override
  void didChangeLocales(List<Locale>? locales) {
    // TODO: implement didChangeLocales
    super.didChangeLocales(locales);

    print("Locales changed");
  }

It needs to run 'detectLanguage' every time the language changes.

2 Answers

Yes, it is possible. Take a look on this example:

@override
  Widget build(BuildContext context) {
    Locale myLocale = Localizations.localeOf(context);

_customFunction();

    return Scaffold(
      appBar: AppBar(
        title: 'Title'),
      ),
      body: Text(myLocale.languageCode == 'fr' ? 'Bonjour!' : 'Hello!'),
    );
  }

You can use Getx library and use:

return GetMaterialApp(
     locale: Get.deviceLocale,   //returns Locale('<language code>', '<country code>')
);

from there you can store it in a variable and once the device language update changes so does the var and there you link your desired function.

Related