flutter 如何使简单的本地化按钮切换语言的应用程序?

44u64gxh  于 2022-12-14  发布在  Flutter
关注(0)|答案(2)|浏览(287)

我正在使用简单的本地化包在2种语言的应用程序,,我需要用一个按钮切换语言。我怎么能做到这一点?

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

slsn1g291#

有课解释正确的制作方法:
Source_code_in_github
Explain Localization with provider and shared preferences
您应该遵循以下步骤:
1.添加软件包providershared_preferneces
1.创建文件夹,并将其命名为l10n
1.在l10n文件夹中添加语言json文件,名称为*.arb,即app_ar.arbapp_en.arb
1.在l10n文件夹中添加Dart文件,并将其命名为:l10n.dart .
1.在arb文件中写入您需要的内容,如下所示:"youKey":"your_value键的第一个字母必须是小写字母camelCase,no _ nor -.即

{
    "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,它将生成包含你的语言的所有属性的类。
1.使用以下代码添加新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函数:

Future<void> main(List<String> args) async {
  WidgetsFlutterBinding.ensureInitialized();
  await SharedPref.getLang();
  runApp(const MyApp());
}

然后在MyApp类中返回提供程序,如下所示:

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.最后在任何类中调用该语言,如我的示例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,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
kupeojn6

kupeojn62#

您需要导入简易本地化包

import 'package:easy_localization/easy_localization.dart'

然后传递参数('ar '或' en')

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

相关问题