Instance member 'setCurrentScreen' can't be accessed using static access - firebase

I am trying to add Firebase Analytics to my flutter app to display different screen names on the dashboard. I used a method that I found here on stackoverflow in this link:
How do I track Flutter screens in Firebase analytics?
I added this code in a separate file:
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/widgets.dart';
// A Navigator observer that notifies RouteAwares of changes to state of their Route
final routeObserver = RouteObserver<PageRoute>();
mixin RouteAwareAnalytics<T extends StatefulWidget> on State<T>
implements RouteAware {
AnalyticsRoute get route;
#override
void didChangeDependencies() {
routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute<dynamic>);
super.didChangeDependencies();
}
#override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}
#override
void didPop() {}
#override
void didPopNext() {
// Called when the top route has been popped off,
// and the current route shows up.
_setCurrentScreen(route);
}
#override
void didPush() {
// Called when the current route has been pushed.
_setCurrentScreen(route);
}
#override
void didPushNext() {}
Future<void> _setCurrentScreen(AnalyticsRoute analyticsRoute) {
print('Setting current screen to $analyticsRoute');
return FirebaseAnalytics.**setCurrentScreen**(
screenName: screenName(analyticsRoute),
screenClassOverride: screenClass(analyticsRoute),
);
}
}
enum AnalyticsRoute { screenName }
String screenClass(AnalyticsRoute route) {
switch (route) {
case AnalyticsRoute.screenName:
return 'screenName';
}
throw ArgumentError.notNull('route');
}
String screenName(AnalyticsRoute route) {
switch (route) {
case AnalyticsRoute.screenName:
return '/screenName';
}
throw ArgumentError.notNull('route');
}
I then added the route observer in the screen that I want to track.
The setCurrentScreen method is not working well and the app is not building. Any suggestions on what I could do to build it.

From the FlutterFire documentation on screen tracking:
await FirebaseAnalytics.instance
.setCurrentScreen(
screenName: 'Products'
);

Related

how to use singleton firebase service on Flutter?

I have 4 pages. I called getRide() method in every 4 pages. it's means 4 times database call. Am I right? Is it possible to create a singleton for this scenario?
Firebase Service:
class FirebaseService {
final Firestore _db = Firestore.instance;
Stream<List<RideModel>> getRide() {
return _db.collection('ride')
.snapshots()
.map((list) => list.documents.map((doc) => RideModel.fromFirestore(doc))
.toList());
}
}
Calling Method:
#override
void initState() {
super.initState();
db.getRide().listen(getRide);
}
void getRide(List<RideModel> model) {
if (!mounted) return;
setState(() {
rideModel = model;
});
}
I can't pass rideModel through Navigator. because when change data in ride collection need to change 4 pages UI.
Someone tells me this answer is correct for the above problem.
I found this way to solve this problem.
I used get_it package and create service locator,
GetIt locator = GetIt.instance;
void setupSingletons() async {
locator.registerLazySingleton<FirebaseService>(() => FirebaseService());
}
And then added to the main class
void main() {
setupSingletons();
runApp(MultiProvider(
providers: globalProviders,
child: MyApp(),
));
}
And every screen I added,
class _Screen1 extends State<Screen1> {
// final db = FirebaseService();
FirebaseService db = GetIt.I.get<FirebaseService>();

How to know FirebaseRecyclerAdapter query is zero or not, exist or not

How to know FirebaseRecyclerAdapter query is zero or not, exist or not
I find some instructions on
https://github.com/firebase/FirebaseUI-Android/tree/master/database
it says:
Data and error events
When using the FirebaseRecyclerAdapter you may
want to perform some action every time data changes or when there is
an error. To do this, override the onDataChanged() and onError()
methods of the adapter:
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(options) {
// ...
#Override
public void onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
}
#Override
public void onError(DatabaseError e) {
// Called when there is an error getting data. You may want to update
// your UI to display an error message to the user.
// ...
}
};
When I tried to use as follow:
mAdapter = new FirebaseRecyclerAdapter<Place, PlaceViewHolder>(options)
{
#Override
public void onDataChanged(DataSnapshot dataSnapshot)
{
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
if (dataSnapshot.exists())
{
Log.d(TAG,"data exists");
}
else
{
Log.d(TAG,"No data exists");
}
}
#NonNull
#Override
public PlaceViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
Error message is:
Method does not override method from its superclass
So how can I solve this problem, Thank you.
I found the answer from another page:
https://www.programcreek.com/java-api-examples/?api=com.firebase.ui.database.FirebaseRecyclerAdapter
#Override
public void onDataChanged()
{
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
if (getItemCount() == 0)
{
Log.d(TAG,"No data exists");
}
else
{
Log.d(TAG,"data exists");
}
}

How to cancel firebase async requests in flutter instead of checking mounted

I have a flutter app talking to the Firebase Realtime Database. I get the data asynchronously, obviously, but my UI allows the user to move to a different part of the app, which means by the time the request completes, the Widget may be unmounted. Best practices say to cancel the async work instead of checking the mounted property but I cannot seem to figure out how to do this for some reason.
#override void initState() {
super.initState();
firebaseRealtimeReference.child('myData').once().then((results) {
if (mounted) {
setState(() {
_myLocalData = results;
}
}
}
/* Alternately with async/await: */
_myLocalData = firebaseRealtimeDatabaseReference.child('myData').once();
}
#override Widget build(BuildContext context) {
return new MyWidget(_myLocalData);
}
#override dispose() {
// Instead of checking mounted in the future, I should instead
// cancel the work in progress here.
super.dispose();
}

Moving cloud firestore collection

I have a scenario in which I want to move my top level, in other words first, collection to the third level. Is the only way to go about this to use third party import-export software with manipulation to do this, or is there a firestore feature that I am missing?
All help will be greatly appreciated.
TopLevel>Documents>ThirdLevel, where top level is the first collection in the db. Just to give a better picture of what I am trying to say.
Firestore has no ability to move collections or documents. Instead, you can copy documents. You'll have to write code to read the contents of a document, then write those contents to a document in a new location, then delete the original document.
I know it's an old question, but just in case someone else needs this. It's now possible using google's cloud shell.
Details available in this link:
https://firebase.google.com/docs/firestore/manage-data/export-import
You have two options to export specific collections, modify them, then import them, or export the whole bucket, then import it back. As I understood you can't mix the operations for example export all and import specific collections.
Note: I believe you'll be charged for the read and write of all documents exported and imported. And billing must be activated.
maybe this can help
public void moveFirestoreDocument(DocumentReference fromPath, final DocumentReference toPath) {
fromPath.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
toPath.set(document.getData())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
fromPath.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}

Firebase - Keep user logged in when they close app [duplicate]

Thank to Firebase the user can logged with the help of G+, Facebook or Twitter. When they are logged, everything is fine.
When the Android app is closed and re-opened, how to reenable the previous succeed logged user with the Firebase API. It is not explained neither in the app demo or in the documentation.
For exemple for Facebook, the sdk seems to save the token, that 's why the button is at connected state (showing that you can disconnect). But what about Firebase and for other authentication systems.
Thanks to the #Frank-van-Puffelen answer, I had some trials until I get something relevant (at least for me : comment are welcome to improve).
I have based my OAuth architecture into 3 mains components :
fdsfds
One single AuthStateListener that is located in the Application.
One Utils Singleton OAuthManager that deal with all authentication process
One or Many Activities that deals with Authentification user interaction (Signin Buttons and so on)
Application Class
FacebookSdk.sdkInitialize(this);
Firebase.setAndroidContext(this);
Firebase.getDefaultConfig().setLogLevel(Logger.Level.DEBUG);
Firebase.getDefaultConfig().setPersistenceEnabled(true);
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
// user is logged in
// create a partialUser from authData
OAuthManager.getDefault().setAuthenticatedUser(authData);
// fetch, merge and save back the partialUser with server registerUser.
OAuthManager.getDefault().startFetchingUserInfo();
} else {
// user is not logged in
// Try to retrieve the user from Facebook SDK
// Try to retrieve the user from "Token and Id save in Android Preferences (in case of issue, or cache reset from Firebase))
// In retrieve is not possible, clean auth data
OAuthManager.getDefault().retrieveOAuth(MilleZimU.getInstance());
}
}
});
OAuthManager
Here is every services that deal with authentication (part has been copy from the Firebase dedicated demo activity)
SignInActivity
Here only remain the part that deal with UI interaction.
Retreiving ?
I'm not sure this is necessary, but case to case (maybe due to crash or update of the app), authentication status where different from Firebase|Prefs|FacebookSdk. I will see with time.
You'll need to add a AuthStateListener. This is described in the Firebase documentation on Monitoring Authentication. From there:
Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.addAuthStateListener(new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
if (authData != null) {
// user is logged in
} else {
// user is not logged in
}
}
});
For anything related to Firebase Authentication on Android, the dedicated demo app is a great next stop. But be sure to first read the documentation, they're not half bad as far as docs go.
Create a BaseActivity class and make sure all other Activities in the app extends that class. The use 'instanceOf' to send user to LoginActivity if authData is null from AuthListener.
package com.mabiri.mabiristores;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.client.AuthData;
import com.firebase.client.Firebase;
import com.mabiri.mabiristores.login.CreateAccount2Activity;
import com.mabiri.mabiristores.login.CreateAccountActivity;
import com.mabiri.mabiristores.login.LoginActivity;
import com.mabiri.mabiristores.login.MapsActivity;
import com.mabiri.mabiristores.utils.Utils;
public class BaseActivity extends AppCompatActivity {
protected Firebase.AuthStateListener mAuthListener;
protected Firebase mFirebaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseRef = new Firebase(YOUR_FIREBASE_URL);
if (!((this instanceof LoginActivity) || (this instanceof CreateAccountActivity)
|| (this instanceof CreateAccount2Activity) || (this instanceof MapsActivity))) {
mAuthListener = new Firebase.AuthStateListener() {
#Override
public void onAuthStateChanged(AuthData authData) {
/* The user has been logged out */
if (authData == null) {
//Stop services and clear sharedPreferences if any
/*Take user to login screen*/
takeUserToLoginScreenOnUnAuth();
}
}
};
mFirebaseRef.addAuthStateListener(mAuthListener);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/* Inflate the menu; this adds items to the action bar if it is present. */
getMenuInflater().inflate(R.menu.menu_base, menu);
return true;
}
private void takeUserToLoginScreenOnUnAuth() {
/** Move user to LoginActivity, and remove the backstack */
Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
protected void logout() {
/**Unauthenticate user from firebase*/
mFirebaseRef.unauth();
}
/**
* Show error toast to users
*/
protected void showErrorToast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
Yup I have struggle with this as well, but a quick update on this issue, you cannot use the (and please correct me if i'm wrong):
Firebase ref
anymore, what you should do is declare as a global
private FirebaseAuth mAuth;
and then use this object on the listener:
mAuth = FirebaseAuth.getInstance();
and only after that you can use the listener
mAuth.addAuthStateListener(mAuthListener);

Resources