How to pass a url(data) or message to app using FCM in flutter?
How to pass a URL throw FCM in a flutter, I already implemented an FCM and received notification, but can't pass data, how to implement that?
A URL as data message from firebase to app using FCM
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
@override
void initState() {
super.initState();
firebaseCloudMessaging_Listeners();
}
void firebaseCloudMessaging_Listeners() {
if (Platform.isIOS) iOS_Permission();
_firebaseMessaging.getToken().then((token){
Navigator.push(context, MaterialPageRoute(
builder: (context) => PageStack(pages: ContactUs(test: token,), title: "Contact Us", back: true,)));
print(token);
});
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
},
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
},
);
}
void iOS_Permission() {
_firebaseMessaging.requestNotificationPermissions(
IosNotificationSettings(sound: true, badge: true, alert: true)
);
_firebaseMessaging.onIosSettingsRegistered
.listen((IosNotificationSettings settings)
{
print("Settings registered: $settings");
});
}
See also questions close to this topic
-
Flutter firebase_database get children
Hi I want to deserialise the snapshot from the realtime database to a Company object and add it to a _companies list. But I keep getting an error...
This is what I have so far:
List<Company> _companies = []; @override void initState() { // TODO: implement initState super.initState(); getItems().then((list){ print("Now the list is here"); setState(() { for (int i=0; i < list.length; i++) { Map<String, dynamic> map = list[i]; Company company = new Company.fromMap(map); _companies.add(company); } }); }); } static Future<List> getItems( ) async { Completer<List> completer = new Completer<List>(); FirebaseDatabase.instance .reference() .child("Companies") .once() .then( (DataSnapshot snapshot) { List map = snapshot.value; //It fails here completer.complete(map); } ); return completer.future; }
This is my Company class:
class Company { String key; String category; String company_name; String company_url; String country; String description; String email; String faq_url; String instagram_url; String logo_url_image; String p_category; String parent_company_ok; String timestamp; Company(); Company.fromSnapshot(DataSnapshot snapshot) : key = snapshot.key, category = snapshot.value['category'], company_name = snapshot.value['company_name'], company_url = snapshot.value['company_url'], country = snapshot.value['country'], description= snapshot.value['description'], email = snapshot.value['email'], faq_url = snapshot.value['faq_url'], instagram_url = snapshot.value['instagram_url'], logo_url_image = snapshot.value['logo_url_image'], p_category = snapshot.value['p_category'], parent_company_ok = snapshot.value['parent_company_ok'], timestamp = snapshot.value['timestamp']; }
How ever, it fails in getItems( ) on
List map = snapshot.value;
. With the exeption:_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'List<dynamic>'
Also if anyone can provide the code for showing the children in a List widget I would be very happy :)
Here is my data structure in firebase realtime database:
-
Get Identity Provider tokens after creating user in Firebase
I am working on a web app that has "Sign in with Google" and "Login with Facebook" buttons. After user successfully signs into the app backed by Firebase, I want to be able to make API calls to their Google and Facebook data. Example is fetch their photos from Google Photos or Facebook.
Normally this is easy to do when you use Google Auth APIs on web and on signing in, you get Auth Code that you can pass to your server and server exchanges that one-time-use code for Access Token and Refresh Token and store them on server side for any future API calls. Here is a link to tutorial for this approach - https://developers.google.com/identity/sign-in/web/server-side-flow
With Firebase being my backend and with FirebaseUI authenticating users to my web app, how can I get the code that I can pass to Firebase Function which can then exchange it for Access Token and Refresh Token and save it into Firestore for further API calls.
-
Root Controller UINavigationBar disappears after user logout with Firebase
I'm facing a slight problem with my UINavigationBar.
I have a an Initial Root View Controller (ViewController) followed by 2 View Controllers (LoginMRNViewController and LoginOTPViewController) that are used to login the user with One Time Password. I also have NavigationController used to navigate the user to his/her homepage after logging in. In the homepage, I have a (Logout) button, that logs out the user with Firebase and navigates him/her to the Initial Root View Controller (ViewController).
The UINavigationBar works like a charm, however, whenever the user logout, he is navigated to the Initial Root View Controller (ViewController) but the UINavigationBar completely disappears!
My logout function:
@IBAction func logoutPressed(_ sender: Any) { do { try Auth.auth().signOut() self.performSegue(withIdentifier: "goToLoginScreen", sender: self) print ("User logged out") } catch let error { print ("Failed to logout with error", error) } }
Here's how my Storyboard looks like.
EDIT:
I tried to put this in my Initial Root View Controller (ViewController) and the other 2 View Controllers (LoginMRNViewController and LoginOTPViewController) in the ViewWillAppear method, but unfortunately it did not work.
self.navigationController?.setNavigationBarHidden(false, animated: false) tabBarController?.tabBar.isHidden = false
Here's how my updated Storyboard look like.
-
How to get StreamSubscription from StreamBuilder
When adding a listener to a RxDart
PublishSubject
I get aStreamSubscription
. I can then use theStreamSubscription
to pause and resume, is there any way to do that with aStreamBuilder
? -
How to combine multi data steams in one BLOC?
I have a widget to represent list of stores sorted by nearest to the user current locations also filtering should be applied.
Data in:
- Stores data coming from stream of Firestore collection
- Current user location from geolacator.
- Filtering options from shared preferences (can be changed any time)
- List sorting mode selected by user
Data out: Filtered, sorted, list of stores.
What pattern is best practice in this case?
-
How to convert a List<Map<String, dynamic>> inside a Map<String, dynamic> to JSON in Dart?
I'm trying to send a
Map<String, dynamic>
, and one of thedynamic
is actually aList<Map<String, dynamic>>
.I assemble it like that :
Packet packet = Packet( datas: stocks.map((stock) => stock.toJson()).toList(), ); String json = jsonEncode(packet);
The problem is what's being sent is actually this :
{ "datas": { "rows": "[{NoArticle: 051131626638, Description: Ruban pour tapis, qty: 5}]" } }
The expected output is this :
{ "datas": { "rows": [{ "NoArticle": "051131626638", "Description": "Ruban pour tapis", "qty": 5, }] } }
I want to send a
List<Map<String, dynamic>>
, not aString
. How do I do that? -
Flutter: How to show a CircularProgressIndicator before WebView loads de page?
I'm using the webview_fluttter plugin, but I can't find a way to show a CircularProgressIndicator before the webview shows the page...
What's the equivalent of Androids WebViewClient onPageStarted/onPageFinished?
WebView( initialUrl: url, onWebViewCreated: (controller) { }, )
thank you
-
Flutter - Error while parsing timestamp in GCM event
I'm building an Android app with Flutter which will receive push notifications. I've got Firebase Cloud Messaging setup and pretty much working, such that I can send the following payload to a valid token and the notification and data are received.
Using url https://fcm.googleapis.com/fcm/send
{ "to":"<valid-token>", "notification":{ "body":"BODY TEXT","title":"TITLE TEXT", "sound":"default" }, "data":{"message":"This is some data"} }
My app receives it correctly and can deal with it. The only slight wrinkle is that I get the following exception thrown in the debug:
W/FirebaseMessaging( 4777): Error while parsing timestamp in GCM event W/FirebaseMessaging( 4777): java.lang.NumberFormatException: Invalid int: "null"
And when I remove "notification":
{ "to":"<valid-token>", "data":{"message":"This is some data"} }
The exception does not occur and push notification does not appear But the data is received in the parts of the code below.
_firebaseMessaging.configure( onMessage: (Map<String, dynamic> message) async { print('on message $message');// <==== }, onResume: (Map<String, dynamic> message) async { print('on resume $message');// <==== }, onLaunch: (Map<String, dynamic> message) async { print('on launch $message');// <==== }, );
How can I have both notification and data in one request?
-
Required to unsubscribe from FCM Topics?
I am using Firebase (FCM) in a project, where I use the topic feature to send out daily notifications to many different users in various timezones. Notifications are always sent out, when the user's time is 12:00PM, in order to achieve this, I create a unique topic every day, for the batch of users I am going to notify. At the moment our topics could look like: x_daily_notification_1550152751 - Previously I had a system that would create static topics based on the timezone, so users could be subscribed to a topic like: x_daily_notification_europe_london, but this proved to be too unreliable and hard to manage, due to users moving between timezones.
The way the system works is based on research and advise from this question I made late last year: FCM topic limits and expiration/invalidation of old unused topics?
So to sum it up:
- Bulk subscribe users to a topic
- 5 minutes later, send out the topic. The delay is due to not knowing if FCM waits for all the bulk subscriptions to process, before sending out the notifications
- 10 mins after sending the topic, unsubscribe all tokens from the topic again, deleting the topic from FCM.
The reason for these delays, is that I have noticed that sometimes we do not get the notifications. The only reason I can think of, is because we send and unsubscribe the topic too fast, so if 100K users were to be notified and we deleted it straight away, only a few would get it. It seems that FCM does not wait for one request to finish before another is processed.
Even though I wait 10 minutes before I unsubscribe, it seems that sometimes not all users get notified, which could mean that they were not processed before I unsubscribed them again, so I would like to wait longer before I unsubscribe everyone from the topic, to ensure that they have received the notification. The first solution I thought of was to just wait, until the next batch is ready to be processed and then delete the previous topic, which would be about an hour later, where I can be more or less sure that everyone has received the notification at that point.
My real question is, do I need to unsubscribe at all? It could get messy on Firebase' end, but surely they have systems in place to handle this, as it does not mention anything in the documentation about cleaning up.
-
Xamarin Ios Firebase cloud messaging
I have implemented firebase in my xamarin ios project. FCM token is getting generated, but when I am pushing a notification from firebase console nothing is happening. Can anyone tell me what wrong I am doing? I have used packages such as
- Firebase.ios.InstanceID - 2.0.4,
- Firebase.ios.Core - 4.0.8,
- Firebase.ios.CloudMessaging - 2.0.4