I integrated firebase_core and firebase_analytics into my flutter web project. Everything is working fine when running in localhost but after I deployed to production site, the firebase stop working and exception was catch using try catch.
PlatformException(channel-error, Unable to establish connection on channel., null, null)
Here is my firebase version in pubspec.yaml
firebase_core: ^2.4.1
firebase_analytics: ^10.1.0
Here is my code when initialized firebase
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
} catch (e) {
debugPrint('Firebase Error : $e');
}
setPathUrlStrategy();
runApp(const MyApp());
}
I followed every instruction at the firebase official doc and even redo the entire firebase installation again but the problem still existed. I have searched in stackoverflow and the flutterfire github, so far no solution for my problem here.
Does anyone know what is going on with my firebase integration?
Related
I'm trying to call a very simple cloud function from my Flutter app following the FlutterFire docs, but I'm getting a pretty unreadable error. The error occurs whether I'm using the emulators, or attempting to call the function fully deployed with Firebase.
My cloud function code:
import * as functions from "firebase-functions";
export const ping = functions.https.onCall(() => ({ ping: "pong" }));
And my Flutter code in main.dart:
import 'package:cloud_functions/cloud_functions.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:my_app/firebase_options.dart';
import 'package:my_app/my_app.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); // Uses options configured by FlutterFire CLI
// Does not work regardless of whether this line is commented out
// FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);
HttpsCallable ping = FirebaseFunctions.instance.httpsCallable('ping');
await ping(); // Exception thrown on this line
runApp(const MyApp());
}
When running this code, I get a FirebaseFunctionsException ([firebase_functions/17999] An internal error has occurred, print and inspect the error details for more information. error:
Even as I dive deeper into the call stack, I'm not able to get any helpful information. Setting a breakpoint in the call method of MethodChannelHttpsCallable shows me that the exception is thrown when calling the MethodChannelFirebaseFunctions.channel.invokeMethod method, but I can't see any immediately obvious reason why that would be failing.
I'm using other FlutterFire libraries in my app (specifically Auth and Firestore), with no problems at all, both with the emulator and the deployed Firebase project.
I found out how to solve this problem.
In the Emulator UI, add a user in the Authentication tab and make your App login with him only once. Then you can logout and delete this user.
After that my function stopped giving error 17999 and it worked normally.
I've followed the tutorial for implementing the Facebook Login from
https://firebase.flutter.dev/docs/auth/social/
Which is the official documentation, my function is literally just:
facebookLogin() async
{
final LoginResult loginResult = await FacebookAuth.instance.login(); // final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(loginResult.accessToken!.token);
// var credentials = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
}
I've commented the following function to isolate the problem.
On the console i get the following:
Performing hot reload...
Reloaded 1 of 1031 libraries in 908ms.
Lost connection to device.
And no exceptions nor errors.
Has anyone faced the same problem before?
I'm using:
flutter_facebook_auth: ^4.1.1
firebase_core: ^1.13.1
firebase_auth: ^3.3.9
In my pubspec.yaml
Is there any way to debug this problem further and find the problem?
Please ensure that you followed the setup steps one by one, and they are:
Ensure the "Facebook" sign-in provider is enabled on the Firebase Console. with the Facebook App ID and Secret set
follow the steps in the plugin (flutter_facebook_auth) documentation to ensure that both the Android & iOS Facebook SDKs have been initialized correctly
Please note that firebase flutterfire uses: flutter_facebook_auth: '^3.5.0' in their documentation and the latest version of that package 4.1.1 untill this day (3/4/2022)
It can be an issue with info.plist configuration for flutter deep-linking.
Did you setup it for your app?
https://docs.flutter.dev/development/ui/navigation/deep-linking
to be more specific you should have only one CFBundleURLTypes section in your info.plist
I had exactly the same problem. Here is how I solved.
In Info.plist, I had 2 sessions called "CFBundleURLTypes", one for Facebook Login, and another one for Google login. Apparently you can only have one CFBundleURLTypes session.
So the solution was to merge everything into a single CFBundleURLTypes session.
I want to include Firebase App Check for Firebase Storage in my Android Flutter App.
Therefore I was following the official documentation: https://firebase.flutter.dev/docs/app-check/usage.
This is my Kotlin MainActivity:
import android.os.Bundle
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.debug.DebugAppCheckProviderFactory
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(/*context=*/ this);
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance())
super.onCreate(savedInstanceState)
}
}
and this is my main():
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseAppCheck.instance.activate();
runApp(MyApp());
}
I also added this to my app/build.gradle
dependencies {
implementation 'com.google.firebase:firebase-appcheck-debug:16.0.0-beta01'
}
When I make a request to firebase storage, I would expect something like this in my console:
D DebugAppCheckProvider: Enter this debug secret into the allow list
in the Firebase Console for your project:
123a4567-b89c-12d3-e456-789012345678
Instead, I'm getting an error:
Error getting App Check token; using placeholder token instead. Error:
com.google.firebase.FirebaseException: Error returned from API. code:
403 body: Requests from this Android client application are
blocked.
Did I miss something here? I am using a real Android device with flutter debug build.
Try to download your google-services.json again.
If this does not help, might need to add/re-add your debug key's SHA-1 certificate after doing so, get new google-services.json
Apparently being blocked by firebase means your API key is configured improperly.
If you are getting this error:
Error: com.google.firebase.FirebaseException: Error returned from API. code: 403 body: App attestation failed.
Check your SafetyNet provider in the Project Settings > App Check.
You will need to provide SHA-256 fingerprint of your app's signing certificate. (would also suggest increasing token live time)
I had exactly the same problem in one of my projects for an Android app. I found the solution and I'm sure it's a solution for flutter apps too.
If you have done all the steps correctly to set up the application for App Check, then install the application in debug mode.
In the logs of the application you will find the secret debug key. You should enter this key in your firebase project in the App Check tab in the debug tokens manager.
Attention
This key has been valid for as long as you have set in the App Check settings.
You have to wait a few minutes.
Now in your project you should remove the code that generates the debug key and replace it with the normal code.
Remove this
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance()
)
Add this
firebaseAppCheck.installAppCheckProviderFactory(
PlayIntegrityAppCheckProviderFactory.getInstance()
)
Now everything should work normally!
The problem is simple! If you leave the code that generates the new key, you generate a new key, thus invalidating the previous one.
I hope I helped!
Footnote
I spent 2 days and nights to find the solution, at one point I thought I was dumb
You have to initialize DebugAppCheckProviderFactory before main activity onCreate done. This works for me.
class MainActivity : FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
FirebaseApp.initializeApp(/*context=*/ this);
val firebaseAppCheck = FirebaseAppCheck.getInstance()
firebaseAppCheck.installAppCheckProviderFactory(
DebugAppCheckProviderFactory.getInstance())
super.onCreate(savedInstanceState)
}
}
Note that this code should be put in debug mode only. You might want to exclude it from release build.
The documentation is very poor about exception handling when using firebase firestore. I'm about to assume there is no such thing to handle specific errors.
I'm currently using the latest dependencies:
firebase_core: ^0.5.0
firebase_auth: ^0.18.0+1
cloud_firestore: ^0.14.0+2
On firebase_auth it is well documented and straight forward how to handle exceptions. There is an exception class named FirebaseAuthException which has a code field that contains the specific error code (unfortunately as a String, but at least it provides something) such as invalid-email, user-disabled, weak-password and so on. It is a nice to have because I can notify the user what went wrong and the program can act accordingly based on these error codes.
On the other hand, unfortunately there is no such thing as FirebaseFirestoreException and the documentation is not much of a help. It shows nothing more than a .catchError() to handle possible exceptions with an error variable with dynamic type so it basically can be anything.
Future<void> addUser() {
// Call the user's CollectionReference to add a new user
return users
.add({
'full_name': fullName,
'company': company,
'age': age
})
.then((value) => print("User Added"))
.catchError((error) => print("Failed to add user: $error"));
}
So my question is if there anything or similar to handle specific exception cases like in FirebaseAuthException with some error codes and stuff. And furthermore how can I identify if it is a FirebaseFirestore exception? Why it does not provide exceptions to make things more comfortable for developers? Or am I missing the point? Please let me know.
Documentation about firebase firestore with flutter: https://firebase.flutter.dev/docs/firestore/usage
I am trying to handle dynamic links within my flutter app and they work perfectly when the app is already installed. The link works fine regardless if the app is open or closed in the background. However when I try to use a link when the app is not installed I am properly brought to the app store, but then once I open the app from within the app store after the install completes it just opens the app and my dynamic link functionality never executes.
My dynamic link is similar to this:
https://startingxi.page.link/?link=https://url-redacted/game/gameId&apn=myapn&isi=mysi&ibi=myibi&st=new%20team%20vs%20&sd=1%20-%202&efr=1
I have tried with both efr=1 and without that.
My flutter code:
#override
void initState() {
super.initState();
initDynamicLinks();
futureInitState = initStateAsync();
}
Future<void> initDynamicLinks() async {
final PendingDynamicLinkData data = await FirebaseDynamicLinks.instance.getInitialLink();
final Uri deepLink = data?.link;
await processDeepLink(deepLink);
FirebaseDynamicLinks.instance.onLink(onSuccess: (PendingDynamicLinkData dynamicLink) async {
final Uri deepLink = dynamicLink?.link;
await processDeepLink(deepLink);
}, onError: (OnLinkErrorException e) async {
print('onLinkError');
print(e.message);
displayFlushBar('$e.message');
});
}
I have tried putting the initDynamicLinks within my futureInitState which is part of my FutureBuilder which does other async stuff at startup. Any help would be appreciated. I'm not sure how to debug this problem and this is my first ios/app dev experience so I'm not sure if there are some logs on the ios device that may help? But at the moment it seems as though I need to deploy to production and get my change live in the app store before I can test anything and that seems less than ideal. But since the dynamic link works in the other use cases I'm stumped on troubleshooting.
Thanks!
Common troubleshooting steps for issues on opening Firebase Dynamic Links after app install is to make sure that value of the ibi parameter matches the app's Bundle ID.
For Google-provided *.page.link domains: in the Capabilities tab of the app's Xcode project, Associated Domains shoudld be enabled, and the following is added in the Associated Domains list: applinks:{your_dynamic_links_domain}.
Also, verify that the AASA of your FDL https://{your_dynamic_links_domain}/apple-app-site-association contains an entry for your app. Verify "appID":"{team-id}.{bundle-id}" values are correct for your app
If these steps didn't work, it's best to reach out to Firebase Support as they have the tools to diagnose deeper into this issue.