Flutter Firebase Cloud Notifications - Hide Notfication when chat is open - firebase

Hey fellow flutter devs,
My app has some chat functionality and I am sending push notifications via Firebase Cloud Functions and then handle them in onMessage, onLaunch and onResume. It works all as intended.
But what my problem is: When the user is currently viewing the Chat, I dont want the user to see a notififcation, since I am already using a stream listener and the user sees the new messages popping up! So no need to get notified here.
My Code for onMessage in CloudMessaging.configure():
onMessage: (Map<String, dynamic> message) async {
print(message);
String chatID = message['data']['chatID'].toString();
//I want to do something like this:
//var routeArguments = ModalRoute.of(naviagtorkey.getCurrentContext).settings.arguments;
//if (routeArguments.contains(chatID)){return;}
String id = message['data']['id'].toString();
if (id != _auth.currentUser.uid) { //this makes sure user who sends message doesnt see get notfied
showOverlayNotification((context) {
return Card(//removed for clarification)
);
}
My Chat class is constructed with a chatID, so if I could somehow access the current Route and see its arguments (its chatID), then I should be able to NOT show any notification when current route arguments equal message['data']['chatID']. Am I wrong? How could I do that. My commented idea just fails quietly.

Ok I was thinking way to complicated. I now just used my instance of shared preferences to keep track of currently opened chat:
onMessage: (Map<String, dynamic> message) async {
SharedPreferences prefs;
prefs = await SharedPreferences.getInstance();
String chatID = prefs.getString('currentChat');
if(chatID==message['data']['chatID'].toString()){
print(chatID);
print(message['data']['chatID'].toString());
return;
}
String id = message['data']['id'].toString();
if (id != _auth.currentUser.uid) { //this makes sure user who sends message doesnt see get notfied
showOverlayNotification((context) {
return Card(//removed for clarification)
);
}
In my Chat in initState() I add the chatID to my SharedPrefs and in dispose() I set it to 'x'. That way, whenever I am currently viewing the chat, SharedPreferences hold the chatID. Maybe that helps someone in the future!!

Related

Cannot get the currentUser's displayName with FirebaseAuth

I have made a sign-in page, and a sign-up page with Firebase Authentication in Flutter and Dart.
After the sign up, I'm trying to retrieve the current user's displayName, however, when I try retrieving it, I seem to get not the current one, but the one that I signed up with before this one.
However, when I for example hot-restart the app, I get the current user's details just fine.
I try to retrieve the current user's displayName property with this code:
static String? getUsername() {
return FirebaseAuth.instance.currentUser?.displayName!;
}
The way I call this, is I initialize a variable to store the username which I get from the method, on a different dart file, different from the signUp page I got. I also call this method in the initState() method.
This is how I sign-up the user and set the displayName:
static void signUpUser(String username, String emailAddress, String password) async {
try {
final credential =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: emailAddress,
password: password,
);
// Here I set the displayName property
await credential.user!.updateDisplayName(username);
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {}
else if (e.code == 'email-already-in-use') {}
} catch (e) {}
}
I tried to use the user.reload(), and FirebaseAuth.userChanges() functions, but these did not seem to fix my problem.
Maybe I'm trying to retrieve the displayName property wrong, what am I missing? I'm quite new to developing my own apps and working with Firebase.
The Future that updateDisplayName returns completes when the call has been made to the underlying Firebase SDK. It does not automatically update the user profile in your application at that point though. That will only happen automatically once every hour (when the SDK refreshes the ID token on which that profile is based), or when the user signs out and in again.
To force a refresh of the profile from your application code outside of those automatic conditions, you can call reload() on the user object.

How Can I Get user id in Flutter with Firebase Authentication?

I am currently trying to get the user id in Flutter with Firebase authentication, and I am initializing a variable in initState because I want to use that variable later for a Future call to fetch data from Firebase Real-time database with future builder. (This doesn't work because I have to reload the screen each time and then, get the user id).
And here is my code,
final FirebaseAuth auth = FirebaseAuth.instance;
User user;
String currentUId;
String currentEmail;
#override
void initState() {
super.initState();
user = auth.currentUser;
// Future.delayed(Duration(seconds: 5));
// sleep(Duration(seconds: 5));
currentUId = user.uid;
currentEmail = user.email;
print(currentUId);
}
I tried using sleep, but it didn't work, Is there another place where I can put sleep in, that will make the program wait for the user id then run the rest of the program?
The auth.currentUser variable is initialized automatically by Firebase, once it's verified the user's authenticate state. But since verifying the state may require a call to the server, this may not have completed by the time your currentUId = user.uid runs.
Instead of trying to wait for the result with sleep calls, I recommend using an auth state listener as shown in the documentation on handling authentication state. This gives you a Stream<User>, which you can easily feed into a StreamBuilder.
For a longer example, also see: How to use .currentUser method in flutter

My Flutter app with Firestore experiences very slow queries when it is resumed from the background on Android

Using Flutter 1.20.2.
My Flutter app uses Firestore as it's backend database. For the current version I am using and throughout the development of this mobile app I have noticed that if my app is in the background for a period of time (could be a few mins) then when I bring the app back into the foreground the queries are very slow to return data. This does not happen on iOS. It only happens on Android.
I use CircularProgressIndicators when my app is busy retrieving data from Firestore. I am using a solid state management setup where each of my Views have a model that extends a BaseModel:
class BaseModel extends ChangeNotifier {
ViewState _state = ViewState.Idle;
ViewState get state => _state;
bool isDisposed = false;
void setState(ViewState viewState) {
_state = viewState;
if (!isDisposed) {
notifyListeners();
}
}
#override
void dispose() {
isDisposed = true;
super.dispose();
}
}
My views then use my view specific models in the following way:
#override
Widget build(BuildContext context) {
return BaseView<MyProfileModel>(
//onModelReady: (model) => model.initialise(Provider.of<User>(context, listen: false)),
onModelReady: (model) => model.initialise(),
builder: (context, model, child) => Scaffold(
resizeToAvoidBottomInset: false,
...
I do not use the AppLifecycleState class yet to do anything special when the app is in the background or is resumed from the background.
When my model is busy retrieving data I show busy circular progress indicators.
The issue is that when I resume my app from the background into the foreground, sometimes the app could be busy for up to 1 minute before it retrieves the data - but only the first time after being back in the foreground. All subsequent calls are normal. Sometimes, it even hangs on first attempt to get data after coming back to the foreground.
I feel like I am not implementing a best practice in relation to resuming an app into the foreground that uses the Firestore database. I have a suspicion that it has something to do with re-establishing the Firestore connection and/or local cache. My App uses the default settings for these.
All of my Firestore API calls are contained in it's own class and I call it the same way each time:
await Firestore.instance
.collection(DBStrings.COLLECTION_AD_MESSAGES)
.document(ad.adId)
.collection(DBStrings.COLLECTION_CHILD_AD_MESSAGES)
.document()
.setData({
// Set fields...
}).catchError((e) {
res = false;
});
Can someone give me some insight into this issue and what could be potentially causing it?
It seem to me that your app is loosing the connection and the data retrieved is from the cache. My suggestion is for you to try to change the backend data from the Firebase console while your app is in the background, then test to see if the retrieved data is the updated or the old one.
If the data is the old one, it means your app could not restore the connection. To overcome this problem you need to check the auth status (if used) and to check the connection status. A simple way to identify connection status and not allow the app to take a very long time before going cache, is to force the app to ask data from remote and provide a timeout, like this:
QuerySnapshot snapshot = await query.getDocuments(source: Source.server).timeout(
_timeoutDuration,
// this or any other callback to handle timeout
onTimeout: () => query.getDocuments(source: Source.cache));
If you are using auth, you can check the auth status by calling:
FirebaseUser currentUser = await _auth.currentUser();
if (currentUser != null) {
// Handle your auth problem here
}
If you are not using auth and the app is retrieving the data from the server after this long period, check if the app would come back faster without the firebase query.

Flutter Firestore take long retrieving data while offline

I am using Firestore in flutter application. Each time user launch the application it retrieves some data from Firestore Cloud.
QuerySnapshot dataSnapshot = await Firestore.instance
.collection('/data')
.getDocuments();
When user opens the application on first time, it required from him to connect online, to get the data, and as Firebase documents say
For Android and iOS, offline persistence is enabled by default. To disable persistence, set the PersistenceEnabled option to false.
So, it should save the data that application have been read before to retrieve it while the device is offline; so user can access application at anytime with the same data that have been read.
The problem is: it takes too long time to retrieve the data while the device is offline, with the same codes and nothing changed!.
I tried to configure how much time it takes? On offline, it takes about 8 minutes and 40 seconds. But while on online, it takes just 10 seconds, maybe less.
So how can I solve this problem?
============
UPDATE
I manged to get more logs about this problem, which after take a lot of time, and will start application with the offline saved data, it prints this log
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
And then take 3 second for example (not much time) and continue with the next works.
I did open a new issue in GitHub too.
Is there a way to limit the time it takes?
And finally, with the help of diegoveloper comment in GitHub issue, I have reached the solution.
This comment
await Firestore.instance
.collection("Collection")
.getDocuments(source: source)
was a good solution if I decided to check source each time and then use it or I can use it in starting of a new Flutter project, but now I already have a lot of codes that need a better solution. So I decided to fork the cloud_firestore package and edit it.
You can find it here: https://github.com/ShadyBoshra2012/flutterfire/tree/master/packages/cloud_firestore
What I have edited:
firestore.dart
// The source of which the data will come from.
static Source _source = Source.serverAndCache;
static Source get source => _source;
Future<void> settings(
{bool persistenceEnabled,
String host,
bool sslEnabled,
bool timestampsInSnapshotsEnabled,
int cacheSizeBytes,
Source source}) async {
await channel.invokeMethod<void>('Firestore#settings', <String, dynamic>{
'app': app.name,
'persistenceEnabled': persistenceEnabled,
'host': host,
'sslEnabled': sslEnabled,
'timestampsInSnapshotsEnabled': timestampsInSnapshotsEnabled,
'cacheSizeBytes': cacheSizeBytes,
});
if (source != null) _source = source;
}
query.dart
source = Firestore.source; Line 92
document_reference.dart
source = Firestore.source; Line 83
How you can use it?
So you can use my forked repository in this way with using connectivity package from Google : https://pub.dev/packages/connectivity .
Add my forked repository in pubspec.yaml file
cloud_firestore:
git:
url: https://github.com/ShadyBoshra2012/flutterfire.git
path: packages/cloud_firestore
Then in your first screen or main
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
await Firestore.instance.settings(source: Source.cache);
} else {
await Firestore.instance.settings(source: Source.serverAndCache);
}
and if you want to refresh the source when change the connection state:
StreamSubscription subscription;
void initState() {
super.initState();
// Check the internet connection after each change
// of the connection.
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) async {
// Check the internet connection and then choose the appropriate
// source for it.
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
await Firestore.instance.settings(source: Source.cache);
} else {
await Firestore.instance.settings(source: Source.serverAndCache);
}
});
}
#override
void dispose() {
super.dispose();
subscription.cancel();
}
So I hope it works with everyone see it, and waiting for Flutter Team to code a better and better solution. Thanks for everyone has participated.
In addition to Shady Boshra's answer you can use FirebaseFirestore.instance.disableNetwork() functionality so your code will look like this:
StreamSubscription subscription;
void initState() {
super.initState();
// Check the internet connection after each change
// of the connection.
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) async {
// Check the internet connection and then choose the appropriate
// source for it.
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
await FirebaseFirestore.instance.disableNetwork();
} else {
await FirebaseFirestore.instance.enableNetwork();
}
});
}

Xamarin android: Async await calls not working when app open by clicking push notification

When I open app by tapping on FCM push notification, The API service calls I am making by using await keyword those are not working. Entire app not returning data.
Code for API calling
var result = await objHomework.GetHomeWorksForStudentPagesAsync(studentId.ToString());
result returning null. if app already open, everything working fine. See the Image below screenshot of app
Notification messages are delivered to OnMessageReceived callback only when the app is in the foreground.
Override the HandleIntent Method of the FirebaseMessageService to work for background as well
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
Actually, I was missing some keys which is necessary for service call authentication in my project. I am getting those keys in MaiActivity but notification click even starting app from somewhere else therefore keys values was null and service calls was not happening.

Resources