Flutter 后台消息国际化

发布于 2025-01-16 04:23:52 字数 386 浏览 4 评论 0原文

在我的 flutter 应用程序中,我想翻译推送通知正文中的一些文本。

用于前台通知。没有问题。

对于背景通知,我使用:

void main() {
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

并且 _firebaseMessagingBackgroundHandler 必须是顶级函数。

那么,由于我这里没有上下文,如何使用我著名的 AppLocalizations.of(context).cancel,

In my flutter app, i want to translate some text in the push notification body.

For foreground notifications. there is no problem.

For backgroud notifiactions i use :

void main() {
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

And _firebaseMessagingBackgroundHandler must be a top-level function.

So, how can i use my famous AppLocalizations.of(context).cancel, since I don't have a context here ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

并安 2025-01-23 04:23:52

由于 _firebaseMessagingBackgroundHandler 是一个顶级函数 - 您可以将 context 作为可选参数传递。这样您就可以访问上下文。

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message,
    {BuildContext? context}){
   
       //Your code
}

Since _firebaseMessagingBackgroundHandler is a top-level function- you can pass context as an optional parameter. So that you can access the context.

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message,
    {BuildContext? context}){
   
       //Your code
}
零度℉ 2025-01-23 04:23:52

我遇到了同样的问题,这是我的解决方案:

@pragma('vm:entry-point')
Future<void> _backgroundMessageHandler(RemoteMessage message) async {
  Locale locale = PlatformDispatcher.instance.locale;
  AppLocalizations? localizations =
    locale.languageCode == 'fr' ? AppLocalizationsFr() : AppLocalizationsEn();
}

基本上我使用了基于平台的 locale 而不是 context 的本地化。

我想知道为什么没有人建议这个,它对我有用。

I faced the same problem and here's my solution:

@pragma('vm:entry-point')
Future<void> _backgroundMessageHandler(RemoteMessage message) async {
  Locale locale = PlatformDispatcher.instance.locale;
  AppLocalizations? localizations =
    locale.languageCode == 'fr' ? AppLocalizationsFr() : AppLocalizationsEn();
}

Basically I used the localizations based on the platform's locale instead of the context.

I wonder why no one suggested this, it works for me.

挖鼻大婶 2025-01-23 04:23:52

在 MyApp 中创建变量 static
Exp:

static BuildContext? mContext;

在 MyApp 的构建函数中

mContext = context;

In MyApp create variable static
Exp:

static BuildContext? mContext;

in build function of MyApp

mContext = context;
不可一世的女人 2025-01-23 04:23:52

这可能是最简单的解决方案。

Locale locale = PlatformDispatcher.instance.locale;
AppLocalizations appLocalizations = await AppLocalizations.delegate.load(locale);

This is probably the simplest solution.

Locale locale = PlatformDispatcher.instance.locale;
AppLocalizations appLocalizations = await AppLocalizations.delegate.load(locale);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文