How to dynamically translate the application

Viewed 352

I followed the steps here to start the translation of my application. I used the .arb file method.

I understand the application get translated when changing the language of the OS, but is it possible, within the application, to toggle the language and make the application dynamically translated?

If so, what should I do? I tried to call the 'load' method, but nothing happened.

Thanks for your help.

1 Answers

Set Locale of MaterialApp and then when you want to change just call

  setState(() {
    _locale = Locale('b'); // Desired locale
  });

Below code changes Locale in every 5 seconds.

  Locale _locale;

  @override
  void initState() {
    _locale = Locale('a');
    Timer.periodic(Duration(seconds: 5), (t) {
      setState(() {
        _locale = _locale == Locale('a') ? Locale('b') : Locale('a');
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      supportedLocales: [
        const Locale('a'),
        const Locale('b'),
        const Locale('c'),
      ],
      localizationsDelegates: [
        MaterialLocalizationDelegateKa(),
        const InfosLocalizationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      locale: _locale,
    );
  }
Related