Unhandled Exception when initializing firebase on windows - flutter

Hi guys first time here on stack overflow.
I am currently building an app using flutter with firebase as the backend.
My target platforms are Windows and android
The android app builds fine
The windows app throws :
ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception:
PlatformException(channel-error, Unable to establish connection on
channel., null, null)
this only happens when I use :
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
I have also tried :
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "myapi",
appId: "appid",
messagingSenderId: "senderid",
projectId: "projectid",
storageBucket: "buckedid",
databaseURL: 'databaseurl',
));
As stated this works fine on android but not windows
I have the latest dependencies for Firebase
I have tried flutter pub outdated and it returns no Firebase dependencies
I have tried flutter pub upgrade
I have tried flutter clear

Hey if you are using the the latest versions of firebase you'd want to follow through the newest way of initializing firebase with firebase CLI. See this https://firebase.flutter.dev/docs/cli starting off by activating firebase cli
have something like this
// Import the generated file
import 'firebase_options.dart'; //this provides the current platform options via the currentPlatform getter from the DefaultFirebaseOptions class
...
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "API KEY",//<<==
appId: "ID",//<<==
messagingSenderId: "IF ANY",//<<==
projectId: "Project ID",//<<==
),
...

Related

Flutter web - Firebase cloud messaging - running OK on localhost, not when I upload to firebase hosting

I am trying to implement FCM for a flutter web project.
When I run the project in the localhost, it works fine. But when I upload it to firebase hosting (After running flutter build web), I am getting errors.
On the main.dart file, I am trying to get the device token:
final fcmToken = await FirebaseMessaging.instance.getToken(
vapidKey:
"my_key");
However, I am getting this error in the console:
main.dart.js:4430 Uncaught MissingPluginException(No implementation found for method Messaging#getToken on channel plugins.flutter.io/firebase_messaging)
I added the firebase messaging package in my pubspec.yaml file:
firebase_messaging: ^14.2.1
Additionally, I added the service worker code as explained here: https://firebase.flutter.dev/docs/messaging/usage/
Here is my index.html script code:
<script>
window.addEventListener("load", function (ev) {
// Download main.dart.js
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
}
_flutter.loader
.loadEntrypoint({
serviceWorker: {
serviceWorkerVersion: serviceWorkerVersion,
},
})
.then(function (engineInitializer) {
return engineInitializer.initializeEngine();
})
.then(function (appRunner) {
return appRunner.runApp();
});
});
</script>
It looks like a problem with the firebase_messaging package, but I'm using the latest one. Also what I can't understand is why it's working in localhost but not production.
Thoughts anyone?
Running flutter clean solved the problem

How to add databaseURL to firebase/flutter project

I got the following error when trying to run a cloud function::
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error: Missing expected firebase config value databaseURL, config is actually{"projectId":"mynotes-b58d2","storageBucket":"mynotes-b58d2.appspot.com","locationId":"us-east4"}
If you are unit testing, please set process.env.FIREBASE_CONFIG
I was told I need to add the following::
"databaseURL":"https://xxxxx.firebaseio.com"
but I dont know where to add it, or what my baseURL is or where to find it
any help is welcomed
update::
i found where to add the info
firebase_options.dart>DefaultFirebaseOptions.
now i need to kmwo what my base url should be
update. i think i got it but i wanna tripple check with somone
I added in two places::
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'XXXX,
appId: 'AAAA',
messagingSenderId: '333333',
projectId: 'mynotes-flutter-project',
storageBucket: 'mynotes-flutter-project.appspot.com',
databaseURL: "https://mynotes-b58d2-default-rtdb.firebaseio.com/",
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'XXXX,
appId: 'AAAA',
messagingSenderId: '333333',
projectId: 'mynotes-flutter-project',
storageBucket: 'mynotes-flutter-project.appspot.com',
iosClientId:
'877208178211-pkk6a4dfdsmh1tfm4ffhdss9lmmjl0mc.apps.googleusercontent.com',
iosBundleId: 'se.pixolity.mynotes',
databaseURL: "https://mynotes-b58d2-default-rtdb.firebaseio.com/",
);
is this correct?
update: its not working :(
I recommend letting the flutterfire CLI generate firebase_options.dart for you, instead of trying to update it manually.
If the file doesn't contain a database URL, that's because you hadn't initialized the database in the Firebase console when you can flutterfire. After creating the database in the console, run flutterfire again to update the firebase_options.dart.

core/no-app No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

When I try to launch my Flutter Web App with Firebase I get the following error in my terminal
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following FirebaseException was thrown building HomePage(dirty, dependencies: [MediaQuery]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
HomePage HomePage:file:///C:/Flutter/pbwebapp/lib/main.dart:37:13
When the exception was thrown, this was the stack:
...
I found other people had problems with this error but in my case I have called Firebase.initializeApp() in my main.dart file and I have also imported firebase_core in my pubspec.yaml
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
name: "pbwebapp",
options: const FirebaseOptions(
apiKey: "...",
authDomain: "..",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
measurementId: "...",
),
);
runApp(MyApp());
}
Does anyone had this problem with Firebase trying to launch a Flutter Web App?
Thanks in advance!
Use Flutter Fire Cli to add flutter firebase packages like auth, messaging etc,
It will automatically configure all the things for you.
https://firebase.google.com/docs/flutter/setup?platform=ios
Okay so somehow removing the name parameter in the Firebase.initializeApp() function worked for me. But I dont know why exactly

Error getting App Check token; using placeholder token instead

My app was working normally since today.I already included Firebase Storage in my Android Flutter App and it works after that today I get AppCheck Errors suddenly. I was not include App Check for our project or not enforced in settings. After that I was following the official documentation for initialization appcheck : 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:
2021-11-21 18:11:51.442 2091-3452/com.sekspir.grind4gain W/ExponenentialBackoff: network unavailable, sleeping.
2021-11-21 18:11:53.500 2091-3452/com.sekspir.grind4gain W/StorageUtil: Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Error returned from API. code: 403 body: App attestation failed.
2021-11-21 18:12:11.136 2091-3633/com.sekspir.grind4gain V/NativeCrypto: SSL handshake aborted: ssl=0xdaa42da8: I/O error during system call, Connection reset by peer
Did I miss something here? I am using a real Android device with flutter debug build.
This is Firestore AppCheck Stats looks both of request income
But in Storage session there are not any request fail or success.
Can you double check that you correctly enabled the enforcement ?
It is required to work with Firebase Storage solutions.
Are you using your app in "PWA" mode or in "Native" mode ?
The Recaptcha may be mandatory depending on how your app is distributed.
await FirebaseAppCheck.instance.activate(
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
);
I'm not sure about your implementation of the appcheck-debug dependency on the Android Native side.
Since it's already implemented by the Flutter library itself, you should remove it.
Personal note : I had troubles with FirebaseAppCheck on some devices, while it was working perfectly on other devices.
This library is still in beta and I would recommend to wait before using it in production.

How to seed the Firebase Storage Emulator?

I'm trying to seed the Firebase Storage Emulator. I've added a json file to my project and I'm trying to upload this file to the Storage Emulator during the seed phase:
await firebaseAdmin
.storage()
.bucket()
.upload(path.join('./data/cars.json'), {
destination: `vehicles/cars.json`,
});
Unfortunately this does not seem to work and I'm running into the following error:
TypeError: Cannot read property 'length' of undefined
The way I did this was by using firebase-tools
firebaseCli.emulators.start({
project: "project-id",
import: "path-to-file.json"
})
This will work only if the firebase emulator setup is done correctly and the data you are trying to import has the correct format.
For the Firebase Storage Emulator to work you need to initialize it in the Admin SDK:
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert('path/to/credential'),
storageBucket: "bucket-name",
});