flutterflutter-localizations

How can I fetch a specific language string from an arb file in Flutter, regardless of the OS language setting?


I am currently using AppLocalizations in my Flutter app to get strings from an arb file based on the language set in the OS. For example, if the OS language is set to English, the app will also display English strings.

However, I'd like to fetch strings in a specific language, different from the one currently set in the OS. For instance, even if the app is set to English, I'd like to display a Dutch string in a particular place.

How can I achieve this and fetch a string in a strictly defined language, regardless of the OS language setting?


Solution

  • Resolved by Localizations.override and Builder. More info here under "Overriding Locale"

    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              // Add the following code
              Localizations.override(
                context: context,
                locale: const Locale('es'),
                // Using a Builder to get the correct BuildContext.
                // Alternatively, you can create a new widget and Localizations.override
                // will pass the updated BuildContext to the new widget.
                child: Builder(
                  builder: (context) {
                    // A toy example for an internationalized Material widget.
                    return CalendarDatePicker(
                      initialDate: DateTime.now(),
                      firstDate: DateTime(1900),
                      lastDate: DateTime(2100),
                      onDateChanged: (value) {},
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      );
    }