簡體   English   中英

如何制作簡單的本地化按鈕來切換應用程序中的語言?

[英]how to make easy localization button to switch languages in the application?

我在 2 種語言應用程序中使用簡單的本地化 Package,我需要使用按鈕切換語言。 我怎么能那樣做?

  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!,
      ),
    ),
  );

有課程解釋正確的制作方法:

Source_code_in_github

使用提供者和共享偏好解釋本地化

您應該遵循一些步驟:

  1. 添加包providershared_preferneces
  2. 創建文件夾並將其命名為l10n
  3. l10n文件夾中添加語言 json 文件作為*.arbapp_ar.arbapp_en.arb
  4. l10n文件夾中添加 Dart 文件,將其命名為: l10n.dart
  5. arb文件中這樣寫你需要的東西: "youKey":"your_value鍵的首字母必須是小寫字母駝峰式,沒有 _ 也沒有 -。即
{
    "application": "application",
    "setting": "settings",
    "langAR": "Arabic",
    "langEN": "English",
    "blue": "blue",
    "green": "green",
    "purple": "purple"
}
  1. 將您的列表語言添加到l10n.dart
    import 'package:flutter/cupertino.dart';

    class L10n {
      static final all = [const Locale('ar'), const Locale('en')];
    }
  1. 在你項目的根空間創建l10n.yaml文件,並寫入:
arb-dir: lib/l10n
template-arb-file: app_en.arb
out-localization-file: app_local.dart
  1. 然后在您的終端運行flutter pub get將生成包含您的所有語言屬性的類。

  2. 使用以下代碼添加新的 dart 文件名,即app_local.dart

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. 添加 dart 文件名,即setting_provider.dart
import 'package:flutter/cupertino.dart';

class SettingProvider extends ChangeNotifier {
  String? local;
  updateLocal(String? lang) {
    local = lang;
    notifyListeners();
  }
}
  1. 添加 dart 文件名,即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. 填寫你的main function:
Future<void> main(List<String> args) async {
  WidgetsFlutterBinding.ensureInitialized();
  await SharedPref.getLang();
  runApp(const MyApp());
}

然后在MyApp class 中返回提供商,例如:

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. 最后調用任何 class 中的語言,如我的示例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,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

你需要導入簡單的本地化 package

import 'package:easy_localization/easy_localization.dart'
 

然后傳遞一個參數('ar'或'en')

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM