Search code examples
androidflutterdartmobileinternationalization

Button to change the language Flutter


I am building an app in Flutter, so far I am using the Internationalization with JSON where the language of the app is based on the language that the user has as default in his phone its working pretty well, but I would like to give the user a chance to change the language without changing phone the system language settings, by only clicking in a button and then the application change the language without going through the settings.

Here is the code:

The Main:

import 'package:flutter/material.dart';
import 'package:flutter_app_darkmode/app_localizations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

  void main() => runApp(MyApp());

  class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) => MaterialApp(
      supportedLocales: [
      Locale('en', "ZA"),
      Locale('pt', "MZ"),
      ],
      localizationsDelegates: [
      AppLocalizations.delegate,
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate
      ],
      localeResolutionCallback: (locale, supportedLocales) {
       for (var supportedLocale in supportedLocales) {
        if (supportedLocale.languageCode == locale.languageCode &&
            supportedLocale.countryCode == locale.countryCode) {
          return supportedLocale;
          } else {
          if (MyHomePage.local != null) {
            for (int i = 0; i < supportedLocales.length; i++) {
              if (MyHomePage.local == supportedLocales.elementAt(i)) {
                return supportedLocales.elementAt(i);
              }}}}}
            return supportedLocales.first;
            },
           home: MyHomePage(),
          );}

         class MyHomePage extends StatefulWidget {
         @override
         _MyHomePageState createState() => _MyHomePageState();

           class _MyHomePageState extends State<MyHomePage> {
           getLocale() {
           Locale myLocale = Localizations.localeOf(context);
            print(myLocale);}

            @override
             Widget build(BuildContext context) {
              getLocale();
               return Scaffold(
                body: Center(
                child: Padding(
                 padding: const EdgeInsets.all(8.0),
                  child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                   Text(
                   AppLocalizations.of(context).translate('first_string'),
                   style: TextStyle(fontSize: 25),
                   textAlign: TextAlign.center,),
                  Text(
                  AppLocalizations.of(context).translate('second_string'),
                    style: TextStyle(fontSize: 25),
                    textAlign: TextAlign.center,),
                    RaisedButton(
                      child: Text('PT'),
                    onPressed: () {},
                     ),],),),),);}}

The app_locations class:

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class AppLocalizations {
final Locale locale;

  AppLocalizations(this.locale);

  static AppLocalizations of(BuildContext context) {
   return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

    static const LocalizationsDelegate<AppLocalizations> delegate =
    _AppLocalizationsDelegate();

    Map<String, String> _localizedStrings;

       Future<bool> load() async {
       String jsonString =
        await rootBundle.loadString('lang/${locale.languageCode}.json');

        Map<String, dynamic> jsonMap = json.decode(jsonString);

       _localizedStrings = jsonMap.map((key, value) {
       return MapEntry(key, value.toString());
        });

        return true;}

       String translate(String key) {
      return _localizedStrings[key];}}

     class _AppLocalizationsDelegate
     extends LocalizationsDelegate<AppLocalizations> {
     const _AppLocalizationsDelegate();

       @override
       bool isSupported(Locale locale) {
       return ['en', 'pt'].contains(locale.languageCode);}

       @override
       Future<AppLocalizations> load(Locale locale) async {
       AppLocalizations localizations = new AppLocalizations(locale);
       await localizations.load();
       return localizations;}

        @override
        bool shouldReload(_AppLocalizationsDelegate old) => false;}

Solution

  • You can set the locale property of MaterialApp with your favourite state management method. For example:

    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => _MyAppState();
    
      static _MyAppState of(BuildContext context) => context.findAncestorStateOfType<_MyAppState>();
    }
    
    class _MyAppState extends State<MyApp> {
      Locale _locale;
    
      void setLocale(Locale value) {
        setState(() {
          _locale = value;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          locale: _locale,
          home: Dashboard(),
        );
      }
    }
    
    class Dashboard extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Column(
          children: [
            TextButton(
              child: Text("Set locale to German"),
              onPressed: () => MyApp.of(context).setLocale(Locale.fromSubtags(languageCode: 'de')),
            ),
            TextButton(
              child: Text("Set locale to English"),
              onPressed: () => MyApp.of(context).setLocale(Locale.fromSubtags(languageCode: 'en')),
            ),
          ],
        );
      }
    }