gpt4 book ai didi

dart - 在 Flutter 中获取 BuildContext 以进行本地化

转载 作者:IT王子 更新时间:2023-10-29 06:36:08 25 4
gpt4 key购买 nike

我尝试使用本地化包在 Flutter 中本地化一个字符串。问题是需要我翻译的位置。它与 UI 无关,而是在我模型的某个深处,我无权访问 BuildContext。有没有其他的可能继续使用翻译功能?

// I don't have a context variable here
MyLocalizations.of(context).trans("foo")

最佳答案

是的。您不需要 BuildContext 来访问字符串。这是我的解决方案:

class Strings {
Strings._(Locale locale) : _localeName = locale.toString() {
current = this;
}

final String _localeName;

static Strings current;

static Future<Strings> load(Locale locale) async {
await initializeMessages(locale.toString());
final result = Strings._(locale);
return result;
}

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

String get title {
return Intl.message(
'Hello World',
name: 'title',
desc: 'Title for the Demo application',
);
}
}

Future<Null> main() async {
final Locale myLocale = Locale(window.locale);
await Strings.load(myLocale);
runApp(MyApplication());
}

现在你可以像下面这样引用一个字符串:

final title = Strings.current.title;

关于dart - 在 Flutter 中获取 BuildContext 以进行本地化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51803755/

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