Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Background messages internationalization

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 ?

like image 484
Idriss Avatar asked Oct 14 '25 16:10

Idriss


2 Answers

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
}
like image 79
ramkumar Avatar answered Oct 17 '25 06:10

ramkumar


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.

like image 40
mcmgnib1 Avatar answered Oct 17 '25 05:10

mcmgnib1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!