So this is the screnario:
I have 2 apps: on both apps i have tested with stateful widget being active screen:
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
class FCMTestPage extends StatefulWidget {
static String name = '/test-fcm';
@override
_FCMTestPageState createState() => _FCMTestPageState();
}
class _FCMTestPageState extends State<FCMTestPage> {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
final List<Message> messages = [];
String token;
@override
void initState() {
super.initState();
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
final notification = message['notification'];
setState(() {
messages.add(Message(
title: notification['title'], body: notification['body']));
});
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
final notification = message['data'];
setState(() {
messages.add(Message(
title: '${notification['title']}',
body: '${notification['body']}',
));
});
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true));
}
@override
Widget build(BuildContext context) {
// getToken();
return Scaffold(
body: ListView(
children: messages.map(buildMessage).toList(),
),
);
}
Widget buildMessage(Message message) => ListTile(
title: Text(message.title),
subtitle: Text(message.body),
);
getToken() async {
token = await _firebaseMessaging.getToken();
print('********************************************');
print(token);
print('********************************************');
}
}
@immutable
class Message {
final String title;
final String body;
const Message({
@required this.title,
@required this.body,
});
}
And these works fine for both apps. Then i started migrating my code from test to real logic. I have initializeApp()
method:
initializeApp() async {
FirebaseMessaging firebaseMessaging = FirebaseMessaging();
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
}
*some unrelated lines were deleted.
And what is interesting is the same code is working for one app, doesnot work for another app. The same code is working in stateful widget and not working within top level function(I've tried to wrap inside class, make function static, doesn't help though) in the same app.
How i solved:
Then i needed to quickly solve the problem and made decision to transform one of my screens to stateful and migrated logic to this screen.
Maybe it is related with garbage collection.