gpt4 book ai didi

json - 使用 json 文件中的动态字符串进行 flutter 国际化

转载 作者:行者123 更新时间:2023-12-03 18:25:04 29 4
gpt4 key购买 nike

到目前为止,我使用的是动态字符串,如本文的解决方案所示:
Flutter internationalization - Dynamic strings

下面是一个例子:

AppLocalizations.of(context).userAge(18)

在 AppLocalizations.dart 上:
userAge(age) => Intl.message(
"My age is $age",
name: "userAge",
args: [age]);
// Return "My age is 18"

但后来我读了这篇关于 flutter 国际化的文章: https://medium.com/flutter-community/flutter-internationalization-the-easy-way-using-provider-and-json-c47caa4212b2
其中显示了如何使用 json 文件作为字符串的资源文件进行本地化。它看起来更方便,所以我更喜欢使用这种方法,但不知道如何从具有动态值的 json 文件中获取字符串。

有什么解决办法吗?

最佳答案

要从 JSON 文件中获取具有动态值的字符串,您可以使用

final age = 18 //user input.
final ageString = 'user_age'
.localisedString()
.replaceAll(new RegExp(r'\${age}'), age)

en.json

{
"user_age": "My age is ${age}",
"user_name_age": "My name is ${name} and age is ${age}"
}

string_extension.dart

extension Localisation on String {
String localisedString() {
return stringBy(this) ?? '';
}
}
另外,你可以做类似的事情,
  String localisedString(Map<String, String> args) {
String str = localisedString();
args.forEach((key, value) {
str = str.replaceAll(new RegExp(r'\${'+key+'}'), value);
});
return str;
}

//usecase
final userName = 'Spider Man'
final age = '18'
final nameAgeString = 'user_name_age'.localisedString({'name': userName, 'age': age})

app_localisation.dart

Map<String, dynamic> _language;

String stringBy(String key) => _language[key] as String ?? 'null';

class AppLocalisationDelegate extends LocalizationsDelegate {
const AppLocalisationDelegate();

// override the following method if you want to specify the locale you are supporting.
final _supportedLocale = ['en'];
@override
bool isSupported(Locale locale) => _supportedLocale.contains(locale.languageCode);

@override
Future load(Locale locale) async {
String jsonString = await rootBundle
.loadString("assets/strings/${locale.languageCode}.json");

_language = jsonDecode(jsonString) as Map<String, dynamic>;
print(_language.toString());
return SynchronousFuture<AppLocalisationDelegate>(
AppLocalisationDelegate());
}

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

关于json - 使用 json 文件中的动态字符串进行 flutter 国际化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997301/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com