Flutter Firebase notification is not displayed in onMessageOpenedApp and onBackgroundMessage - firebase

I have an application Flutter and I use firebase messaging. On most smartphones the message is received normally in all states (onMessage, onMessageOpenedApp, onBackgroundMessage). But on some smartphones, notification doesn't come (onMessageOpenedApp, onBackgroundMessage), I've tried some tips and it didn't work for me. My last attempt was this, top-level function :
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
print(
"Background message: ${message.notification.title}, ${message.notification.body}");
}
void main() {
FirebaseMessaging.onMessageOpenedApp.listen(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(InitApp());
}
I'm using:
firebase_core : ^1.6.0
firebase_messaging : ^10.0.6
Please I need tips on what else I can try to do.

Related

flutterfire crashlytics not enable

not enable crashlyrics in firebase console, after
await Firebase.initializeApp();
FirebaseCrashlytics.instance.crash();
my code
Future<void> main() async {
//runZonedGuarded<Future<void>>(() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError;
FirebaseCrashlytics.instance.crash();//this i also set in initState and build
runApp(const MyApp());
//}, (error, stack) => FirebaseCrashlytics.instance.recordError(error, stack));
}
app/build.gradle:
implementation platform('com.google.firebase:firebase-bom:29.0.4')
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.firebase:firebase-analytics-ktx'
implementation 'com.google.firebase:firebase-crashlytics-ktx'
android/build.gradle:
classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
Tried start app with flutter run --release
also I tried use this example with my options: DefaultFirebaseOptions.currentPlatform: https://github.com/FirebaseExtended/flutterfire/blob/master/packages/firebase_crashlytics/firebase_crashlytics/example/lib/main.dart
I did everything according to the instructions from here https://firebase.flutter.dev/docs/ Getting started and Craslytics
don't have any errors, except for crashlytics not working in the firebase console
The problem was solved by another device, with android 11, with it there was a log about the request for crashlytics
There was no request on my device with 12 android, so far I will put the issue resolved, although I would like to have a solution to the problem for 12 android

Facing 'No Firebase App has been created' while uploading to Firebase Storage in a Flutter app

I want to collect user browsing data for offline backend analysis for a Flutter app. What is the optimal way to do that?
What I am planning to do is run a daily cron on the app that uploads it using the WorkManager package.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
Workmanager().initialize(uploadUserData, isInDebugMode: true);
Workmanager()
.registerOneOffTask('1', 'task1', initialDelay: Duration(seconds: 10));
runApp(MyApp());
}
void uploadUserData() {
Workmanager().executeTask((task, inputData) {
firebase_storage.FirebaseStorage.instance
.ref('/uploads/test_workmanager.txt')
.putString('workmanager test');
return Future.value(true);
});
}
I am facing the following issue while running the above code
E/BackgroundWorker( 6733): errorCode: error, errorMessage: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
I/WM-WorkerWrapper( 6733): Worker result FAILURE for Work [ id=81642715-826f-4d40-b8ec-9d86eab75136, tags={ be.tramckrijte.workmanager.BackgroundWorker } ]
I have checked in multiple ways that firebase is initialized before calling the workmanager task (using firebase.apps.length & .whenComplete)
Update: Many are doubting whether firebase connection is right: basically everything just works if I just call firebase_storage....putString in the main() instead of within Workmanager().executeTask. So, the trouble is only due to Workmanager.
First call await Firebase.initializeApp(); in Workmanager().executeTask() async { }.
I recommend also "awaiting" all the following Firebase actions in the Workmanager task: await firebase_storage.FirebaseStorage.instance.[...]. This is because without await, the Workmanager might consider the task finished and kill the process before the Firebase action finishes.
Full Workmanager example task code with changes:
Workmanager().executeTask((task, inputData) async {
await Firebase.initializeApp();
await firebase_storage.FirebaseStorage.instance
.ref('/uploads/test_workmanager.txt')
.putString('workmanager test');
return Future.value(true);
});
You can call Firebase.initializeApp(); again in the Workmanager().executeTask() method before invoking any Firebase call.

Initializing Firebase Throws an Error - Flutter

While I was trying to set up Firebase, I learned that I need to initialize Firebase after the last updates. But when I run:
Firebase.initializeApp();
I get an error saying:
_CastError (Null check operator used on a null value)
I tried to remove it, afterwords everything worked fine.
This is the code I am running:
Future<void> main() async {
await Firebase.initializeApp();
runApp(SignIn());
}
According to documents this is how you can initialize firebase in your app:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); //Make sure you imported firebase_core
runApp(SignIn());
);
}
Happy Fluttering :)

Flutter FirebaseMessaging onMessage not working

I am trying to push a notification to an IOS flutter app. My flutter main loop looks like this:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
print(await FirebaseMessaging.instance.getToken());
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
alert: true, // Required to display a heads up notification
badge: true,
sound: true,
);
runApp(MyApp());
}
And the initState() of MyApp() looks like this:
#override
void initState() {
super.initState();
FirebaseMessaging messaging = FirebaseMessaging.instance;
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Got a message whilst in the foreground!');
print('Message data: ${message.data}');
if (message.notification != null) {
print('Message also contained a notification: ${message.notification}');
}
});
}
I can't get any of the FirebaseMessaging streams to work. The onMessage/onMessageOpenedApp/onBackgroundMessage() won' work but if the App is closed I can push notifications. But still none of the above streams will have any content.
I push notifications via this python code:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging
cred = credentials.Certificate("auth.json")
app = firebase_admin.initialize_app(cred)
topic = 'test'
apns_config = messaging.APNSConfig(
payload=messaging.APNSPayload(
messaging.Aps(
mutable_content=False,
sound=messaging.CriticalSound('default')
)
)
)
notification = messaging.Notification(
title="FCM Message",
body="This is a Firebase Cloud Messaging Topic Message!"
)
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
notification=notification,
#topic=topic,
token="token_of_device",
apns=apns_config
)
response = messaging.send(message, app=app)
print('Successfully sent message:', response)
Is there a way to fix this problem?
Thanks in advance.
To test notifications on IOS you must have:
Mac (to run from XCode), IPhone (will not work on emulator, because it is the politics of apple: "get all the money from user"), apple dev account (100$/year), set up certificates, ask user for permissions and then test on real Iphone device

Flutter- How can i handle (onPause/OnResume, onStart and OnTerminate) funactionality on flutter using firebase cloud messeging and notifications?

firebase_messaging: ^9.0.0
flutter sdk 2.0.1
I am getting the message notification only when the app is running on background but not for terminate or on process app.
And getting the message A background message could not be handled in Dart as no onBackgroundMessage handler has been registered.
How to handle three functionality (app is running already, app is running on backgroud, app is terminated) into app using the latest version of cloud messegning library?
Here is the code that i have tried to implement.
#override
void initState() {
super.initState();
FirebaseMessaging.instance
.getInitialMessage()
.then((RemoteMessage message) {
print('I am called 1');
});
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
RemoteNotification notification = message.notification;
AndroidNotification android = message.notification?.android;
print('I am called 2');
});
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('I am called 3');
});
}

Resources