Reputation: 418
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 ?
Upvotes: 4
Views: 1178
Reputation: 1991
This is probably the simplest solution.
Locale locale = PlatformDispatcher.instance.locale;
AppLocalizations appLocalizations = await AppLocalizations.delegate.load(locale);
Upvotes: 0
Reputation: 31
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.
Upvotes: 1
Reputation: 236
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
}
Upvotes: 2
Reputation: 35
In MyApp create variable static Exp:
static BuildContext? mContext;
in build function of MyApp
mContext = context;
Upvotes: 0