Flutter Background messages internationalization - flutter

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
}

In MyApp create variable static
Exp:
static BuildContext? mContext;
in build function of MyApp
mContext = context;

Related

Cannot navigate to a specific page when tapping a notification (when app is in background)

I am developing an app in flutter. I used awesome_notification package to show notifications. In awesome_notification, onActionReceivedMethod works fine when an app is in the foreground but does not work when an app is in the background. How to handle this?
#pragma("vm:entry-point")
static Future <void> onActionReceivedMethod(ReceivedAction receivedAction) async {
// code to navigate some page
} // not calling when user tap notification
Also, onMessageOpenedApp function is not triggered when tapping the notification. How to solve this? Kindly help me to resolve this.
FirebaseMessaging.onMessageOpenedApp.listen((message) async {
// code to navigate some page
}); // not calling when user tap notification
I encountered the same problem with local_notification, to pass an information from the vm entry point to the app.
I solved it by doing an isolate sent / receive like this:
//needed for isolate
import 'dart:isolate';
import 'dart:ui';
//outside main
const String channel = 'channel_key';
#pragma('vm:entry-point')
void onReceiveBackgroundResponse(NotificationResponse notificationResponse) async {
final sendPort = IsolateNameServer.lookupPortByName(channel);
sendPort?.send(notificationResponse.actionId);
}
...
//inside main
void listenNotification() {
final receivePort = ReceivePort();
IsolateNameServer.registerPortWithName(receivePort.sendPort, channel);
receivePort.asBroadcastStream().listen((event) {
print(event);
});
}

How To Use GetX Translations On Notifications(On Terminated State)?

GetX translation is not working on notifications that are created when the app is in the terminated state.
This is how I show the notifications. Below translations work in foreground notifications but not in the background (terminated)
showNotification(message){
...
var title = 'some_title'.tr
var body = 'some_body'.tr
...
}
And rest of the code, FirebaseMessaging.onBackgroundMessage(onBackgroundMessage) and onBackgroundMessage defined as required
Future<void> onBackgroundMessage(RemoteMessage message) async {
showNotification(message);
return Future.value();
}
void main() async {
...
FirebaseMessaging.onBackgroundMessage(onBackgroundMessage);
runApp(const MyApp());
}
Note: I know, this issue is happening because the app is not running yet. GetMaterialApp did not run, as a result, GetX didn't work too
Note: I'm not having any issue with navigations or showing notifications.

Calling method in separate Class- Flutter

In my main.dart at the end of a method I call 2 entities, one is within main.dart and works fine, the other is in another Class, _mapItemsExample2.
I have implemented _MyAppState(this._mapItemsExample2); functionality to call it as widget.
void main() {
SdkContext.init(IsolateOrigin.main);
runApp(MaterialApp(
theme: ThemeData(fontFamily: 'DMSans'),
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
MapItemsExample2? _mapItemsExample2;
#override
_MyAppState createState() => _MyAppState(this._mapItemsExample2);
}
class _MyAppState extends State<MyApp> {
final MapItemsExample2? _mapItemsExample2;
_MyAppState(this._mapItemsExample2);
Future<void> intermodalRouter() async{
...
_sendIntermodalDataToSecondScreen(context, mappedValues, dest); //works fine
widget._mapItemsExample2?.showFirstPolylineMapMarkers(deplat, deplong, deplocname);
}
});
}
It will pass data to
class MapItemsExample2 {
void showFirstPolylineMapMarkers(deplat, deplong, deplocname) async {
print('showFirst');
...
But it goes dead and doesn't print or call _showFirstPolylineMapMarkers
I need to call the method to trigger a display of data. No errors showing but even after adding the widget function as suggested it displays nothing and doesnt print readouts
Any guidance appreciated
Thank you
Update
Recieving error in main.dart
2 positional argument(s) expected, but 0 found.
on
final MapItemsExample2 _mapItemsExample2 = MapItemsExample2();
class MapItemsExample2 {
MapItemsExample2(ShowDialogFunction2 showDialogCallback2, HereMapController hereMapController)
: _showDialog2 = showDialogCallback2,
_hereMapController = hereMapController {
void showFirstPolylineMapMarkers(deplat, deplong, deplocname) async {
print('showFirst');
Have tried adding parameters in but they are not recognised
You are using the ?. null-aware operator when calling showFirstPolylineMapMarkers(..), so it will only call it if widget._mapItemsExample2 is not null. Have you checked whether it is null or not at the time you're making this call?
In your code it is apparent that no instance of _mapItemsExample2 is being passed into MyApp() when you call it from main(), since the parameter list is empty. You need to create an instance of it and pass it into MyApp, or get access to a previously created instance to pass in. I don't have enough code to give you a more specific answer.

Flutter GetIn can't find the method of the services

I'm setting up a project with Flutter. I want to register services with GetIn. But I'm not able to find the methods of the service that I want to use.
This is the class locator in which I register the service, for example MongoDBService.
import 'package:app/services/mongodb.dart';
import 'package:get_it/get_it.dart';
final locator = GetIt.instance;
setupLocator() {
locator.registerSingleton<MongoDBService>(MongoDBService());
}
Then when I want to use the MongoDBService I am not able to find the functions that belong to the service.
void connect() async {
await mongo.beginConnection();
}
final mongo = locator<MongoDBService>;
The error is on beginConnection which is not defined. But currently it is defined in the MongoDBService.
Also I setup the locator by calling the setupLocator function in the main.
void main() {
setupLocator();
runApp(const MyApp());
}
Put final mongo = locator<MongoDBService>; in the connect method.
void connect() async {
final mongo = locator<MongoDBService>();
await mongo.beginConnection();
}

Flutter - How to call functions (and variables) between stateful widgets?

I have this function in a widget (homescreen):
void toggleRecording() async {
// HERE IS THE CONFUSION I GUESS
_isRecording = !_isRecording;
recorder = SoundStream(isRecording: _isRecording);
//recorder.toggleRecording(_isRecording);
setState(() {
_isRecording = recorder.isRecording;
});
if (_isRecording) {
startTimer();
_stopwatch.start();
} else {
stopTimer();
_stopwatch.stop();
}
}
It needs to call (trigger) another function in my recorder class:
void toggleRecording() async {
widget.isRecording ////// currently being passed as an argument from homescreen
? {_recorder.stop, await save(_micChunks, 44100)}
: _recorder.start;
}
Also, the boolean variable _isRecording is present in both the classes. How do I sync the state?
In your situation passing reference of function through widgets will work. However best practice of this will be using provider package.
Managing functions from provider will allow you to control functions from all pages.
If you change a variable you can call notifylistener() function inside your provider function. So that you can change state of widget.
I will try to explain it in a glance however this is an important subject of flutter.
Here is my folder structure
At provider folder we define our provider classes.
Firstly i define class which extends changeNotifier class. This is what make this class provider.
Side note: notifyListener() function here calls setState of every widget if you use any variables inside that class and this is what you are searching for.
Then i import it into my main.dart file or whatever file you want. Only condition is being above the widget that you will use provider at.
At last you can use your function at everywhere if you import provider package and define your provider like i did in this code.
At last here is the visualized stucture of provider package.
I wish i explained it well. There is more about it on youtube.
Pass the function to other widget
using Function keyword
Say ContentWidget is your child and ParentWidget is parent
class ParentWidget extends StatefulWidget {
//Do Something
void onSomeFunction()
{
ContentWidget(onTimerUpdate:onTimerClosed)
}
void onTimerClosed()
{
//Perform Operation on Timer Change
}
}
class ContentWidget extends StatefulWidget {
final Function onTimerUpdate;
ContentWidget({
Key key,
#required this.onTimerUpdate,
}) : super(key: key);
void onAnyActionFromChild()
{
widget.onTimerUpdate() //Note () can have any param or can be null
}