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 ?
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With