Home > front end >  how to make easy localization button to switch languages in the application?
how to make easy localization button to switch languages in the application?

Time:12-13

I'm using easy Localization Package in 2 languages Application ,,And I Need To swith langauge using a Button . How could i Do That?

  await EasyLocalization.ensureInitialized();
  log(token);
  runApp(
    EasyLocalization(
      supportedLocales: const [Locale('ar'), Locale('en')],
      path: 'assets/translations',
      startLocale: const Locale('ar'),
      fallbackLocale: const Locale('en'),
      saveLocale: true,
      assetLoader: const CodegenLoader(),
      child: ScreenUtilInit(
        designSize: const Size(411.4, 683.4),
        child: const MyApp(),
        builder: (context, child) => child!,
      ),
    ),
  );

CodePudding user response:

There is lesson explain the right way to make it:

Source_code_in_github

Explain Localization with provider and shared preferences

There are some steps you should follow:

  1. Add packages provider and shared_preferneces.
  2. Create folder name it as l10n.
  3. Add language json file in l10n folder as *.arb i.e app_ar.arb and app_en.arb.
  4. Add Dart file in l10n folder name it: l10n.dart.
  5. Write what you need in arb files like this: "youKey":"your_value first letter of key must be small letter camelCase, no _ nor -. i.e
{
    "application": "application",
    "setting": "settings",
    "langAR": "Arabic",
    "langEN": "English",
    "blue": "blue",
    "green": "green",
    "purple": "purple"
}
  1. add your list language to l10n.dart.
    import 'package:flutter/cupertino.dart';

    class L10n {
      static final all = [const Locale('ar'), const Locale('en')];
    }
  1. Create l10n.yaml file in the root space of your project and write in it:
arb-dir: lib/l10n
template-arb-file: app_en.arb
out-localization-file: app_local.dart
  1. Then in your terminal run flutter pub get that will generate the classes that contain all you properties of your languages.

  2. Add new dart file name i.e app_local.dart with this code:

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class AppLocal {
  static AppLocalizations? _loc;

  static AppLocalizations get loc {
    return AppLocal._loc!;
  }

  static void init(BuildContext context) {
    _loc = AppLocalizations.of(context);
  }
}
  1. Add dart file name it i.e setting_provider.dart:
import 'package:flutter/cupertino.dart';

class SettingProvider extends ChangeNotifier {
  String? local;
  updateLocal(String? lang) {
    local = lang;
    notifyListeners();
  }
}
  1. Add dart file name it i.e shared_pref.dart:
import 'package:shared_preferences/shared_preferences.dart';

class SharedPref {
  static String? lang;

  static addLang(String lang) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    sp.setString('lang', lang);
  }

  static Future<String?> getLang() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    lang = sp.getString('lang');
    return lang;
  }
}
  1. Write in your main function:
Future<void> main(List<String> args) async {
  WidgetsFlutterBinding.ensureInitialized();
  await SharedPref.getLang();
  runApp(const MyApp());
}

and then in MyApp class return the provider like:

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => SettingProvider())
      ],
      child: Builder(
        builder: (context) {
          return MaterialApp(
            supportedLocales: L10n.all,
            locale: Locale(Provider.of<SettingProvider>(context).local ??
                SharedPref.lang ??
                'en'),
            localizationsDelegates: AppLocalizations.localizationsDelegates,
            title: 'Localization',
            home: const HomePage(),
          );
        },
      ),
    );
  }
}
  1. Finally call the language in any class as in my example HomePage:
  Widget build(BuildContext context) {
    AppLocal.init(context);
    SettingProvider prov = Provider.of(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocal.loc.application),
      ),
      body: Column(
        children: [
          Wrap(
            children: List.generate(L10n.all.length, (index) {
              return RadioListTile(
                title: Text(
                  L10n.all[index].languageCode == 'en'
                      ? AppLocal.loc.langEN
                      : AppLocal.loc.langAR,
                  style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.w900,
                  ),
                ),
                value: L10n.all[index].languageCode,
                groupValue: prov.local,
                onChanged: (String? value) {
                  SharedPref.addLang(value!);
                  prov.updateLocal(value);
                },
              );
            }),
          ),
          Center(
            child: Text(
              AppLocal.loc.setting,
              style: TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.w900,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

you need to import easy localization package

import 'package:easy_localization/easy_localization.dart'
 

Then pass a parameter ('ar' or 'en')

ElevatedButton(
   onPressed: () {
      setState(() {context.setLocale(Locale('en')); //ar});
                                  },
  • Related