Flutter Firebase has not been correctly initialized - firebase

I want to use firebase in my app,
I write this:
main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(Myapp());
}
but I got error :
I/ExoPlayerImpl( 5331): Init ba5fb7d [ExoPlayerLib/2.17.0] [generic_x86, Android SDK built for x86, unknown, 30]
E/flutter ( 5331): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.
E/flutter ( 5331):
E/flutter ( 5331): Usually this means you've attempted to use a Firebase service before calling `Firebase.initializeApp`.
E/flutter ( 5331):
E/flutter ( 5331): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization
E/flutter ( 5331):
E/flutter ( 5331): #0 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)
E/flutter ( 5331): <asynchronous suspension>
E/flutter ( 5331): #1 Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)
and this:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
how can I solve it?
can anyone help me, please?

Does it solve the issue if you replace the initializeApp() line with the following?
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);

Related

Flutter FirebaseMessaging onBackgroundMessage Null check operator used on a null value

I'm building an app with firebase with push notifications so the app was running but after I used "flutter clean" this error appears without changing and piece of code
E/flutter (14812): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter (14812): #0 MethodChannelFirebaseMessaging.registerBackgroundMessageHandler (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:180:53)
E/flutter (14812): #1 FirebaseMessagingPlatform.onBackgroundMessage= (package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:102:16)
E/flutter (14812): #2 FirebaseMessaging.onBackgroundMessage (package:firebase_messaging/src/messaging.dart:73:31)
E/flutter (14812): #3 main (package:mitaa/main.dart:37:21)
the error appears in the package firebase_messaging: ^11.2.6
https://firebase.flutter.dev/docs/messaging/usage/
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print("Handling a background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
Blockquote

Unhandled Exception: Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type [duplicate]

This question already has an answer here:
The return type 'void' isn't assignable to 'FutureOr<T>', as required by 'Future.catchError'
(1 answer)
Closed 11 months ago.
I am trying to write a dart program which can register users and upon error print its description which i will eventually use in a Toast but it gives an error on catchError
User? _user = (await _auth.createUserWithEmailAndPassword(
email: email.toString(),
password: password.toString())
.catchError((e) {
print(e.message);
})).user;
I/flutter ( 3113): The email address is already in use by another account.
E/flutter ( 3113): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Invalid argument(s) (onError): The error handler of Future.catchError must return a value of the future's type
E/flutter ( 3113): #0 _FutureListener.handleError (dart:async/future_impl.dart:181:7)
E/flutter ( 3113): #1 Future._propagateToListeners.handleError (dart:async/future_impl.dart:778:47)
E/flutter ( 3113): #2 Future._propagateToListeners (dart:async/future_impl.dart:799:13)
E/flutter ( 3113): #3 Future._completeError (dart:async/future_impl.dart:574:5)
E/flutter ( 3113): #4 _completeOnAsyncError (dart:async-patch/async_patch.dart:287:13)
E/flutter ( 3113): #5 FirebaseAuth.createUserWithEmailAndPassword (package:firebase_auth/src/firebase_auth.dart)
E/flutter ( 3113):
E/flutter ( 3113):
Try wrapping it in a try...catch bloc it will throw FirebaseAuthException with a message field containing your message
https://firebase.flutter.dev/docs/auth/error-handling/
Split it up like so:
await _auth.createUserWithEmailAndPassword(
email: email.toString(),
password: password.toString(),
).catchError((e) {
print(e.message);
});
User? user = _auth.currentUser;

ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized

I am very new to Dart, and coding in general. I have produced this code after watching tutorials on YouTube. For the most part, I have been able to troubleshoot most of my problems on my own, yet I cannot figure out my most recent errors. I have using firebase for authentication as soon as I write code in main.dart
Future <void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp().then((value) => Get.put(AuthController()));
runApp(const MyApp());
}
and if i run the app, I get the following error
E/flutter ( 5661): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
[core/not-initialized] Firebase has not been correctly initialized.
E/flutter ( 5661):
E/flutter ( 5661): Usually this means you've attempted to use a Firebase service before
calling `Firebase.initializeApp`.
E/flutter ( 5661):
E/flutter ( 5661): View the documentation for more information:
https://firebase.flutter.dev/docs/overview#initialization
E/flutter ( 5661):
E/flutter ( 5661): #0 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)
E/flutter ( 5661): <asynchronous suspension>
E/flutter ( 5661): #1 Firebase.initializeApp
(package:firebase_core/src/firebase.dart:40:31)
E/flutter ( 5661): <asynchronous suspension>
E/flutter ( 5661): #2 main (package:definer_lms/main.dart:10:3)
E/flutter ( 5661): <asynchronous suspension>
E/flutter ( 5661):
My android/app/build.gradle has the following config:
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "getin.******.definer_lms" // edited for security purpose
minSdkVersion 23
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}
.....
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:29.1.0')
implementation 'com.android.support:multidex:1.0.3'
}
.....
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'
}
My android/build.gradle has the following config:
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.10'
}
can someone please find what is wrong here?
You need to write this way :
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp().then((value) {
Get.put(AuthController());
runApp(const MyApp());
});

I have this issue while inserting a new record in firebaseFirestore

I am trying to add new record in Firebase FireStore and i get this exception
E/flutter (11243): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(firebase_core, java.util.concurrent.ExecutionException: java.lang.NullPointerException: Firestore component is not present., null, null)
E/flutter (11243): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (11243): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:177:18)
E/flutter (11243): <asynchronous suspension>
E/flutter (11243): #2 MethodChannel.invokeListMethod (package:flutter/src/services/platform_channel.dart:363:35)
E/flutter (11243): <asynchronous suspension>
E/flutter (11243): #3 MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:31:23)
E/flutter (11243): <asynchronous suspension>
E/flutter (11243): #4 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:73:7)
E/flutter (11243): <asynchronous suspension>
E/flutter (11243): #5 Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)
E/flutter (11243): <asynchronous suspension>
E/flutter (11243): #6 main (package:uccd_etu/main.dart:10:3)
E/flutter (11243): <asynchronous suspension>
E/flutter (11243):
this is my main.dart code
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
and this is the method that will create a new record in firestore database
import 'package:cloud_firestore/cloud_firestore.dart';
class DbServices {
static DbServices instance = DbServices();
late FirebaseFirestore _db;
String _usersCollection = "users";
DbServices() {
_db = FirebaseFirestore.instance;
}
Future<void> createUserInDb(String _uid,String _userName, String _nationalId,
bool _isDisabled, String _password) async{
try{
return await _db.collection(_usersCollection).doc(_uid).set({
"userName":_userName,
"password":_password,
"nationalId":_nationalId,
"isDisabled":_isDisabled,
"timeOfRegistiration":DateTime.now().toUtc()
});
}catch(e){print(e);}
}
}
=======================
flutter doctor output
#
mdobrucki
[√] Flutter (Channel stable, 2.10.1, on Microsoft Windows [Version 10.0.18363.1256], locale ar-EG)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
X cmdline-tools component is missing
Run `path/to/sdkmanager --install "cmdline-tools;latest"`
See https://developer.android.com/studio/command-line for more details.
X Android license status unknown.
Run `flutter doctor --android-licenses` to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/windows#android-setup for more details.
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2019 16.8.3)
[√] Android Studio (version 2020.3)
[√] IntelliJ IDEA Community Edition (version 2021.2)
[√] VS Code (version 1.64.2)
[√] Connected device (4 available)
[√] HTTP Host Availability
! Doctor found issues in 1 category.
the exception applies to a local account who has been removed from their payment handler...the problem needs to be solved with code that identifies the exception parameters, thus handles the cookie payment, and encryption key fingerprint validated with the cookie identifying the user-agent, user, or supervisor. the manager should be you, if you're developing for this kind of exception, and the user should be 'me', owner, or first person to third party apple webkit.

Flutter firebase function error : Response is not valid JSON object

Hello I tried to use firebase function by using Cloud_Functions Pkg but I got error in flutter consel , I tried to pass parameters in function which is UID of user .
Consel Error :
E/flutter (17871): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: [firebase_functions/internal] Response is not valid JSON object.
E/flutter (17871): #0 catchPlatformException
package:cloud_functions_platform_interface/…/utils/exception.dart:21
E/flutter (17871): #1 _rootRunBinary (dart:async/zone.dart:1378:47)
E/flutter (17871): #2 _CustomZone.runBinary (dart:async/zone.dart:1272:19)
E/flutter (17871): #3 _FutureListener.handleError (dart:async/future_impl.dart:166:20)
E/flutter (17871): #4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:716:47)
E/flutter (17871): #5 Future._propagateToListeners (dart:async/future_impl.dart:737:24)
E/flutter (17871): #6 Future._completeError (dart:async/future_impl.dart:547:5)
E/flutter (17871): #7 _completeOnAsyncError (dart:async-patch/async_patch.dart:264:13)
E/flutter (17871): #8 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart)
package:flutter/…/services/platform_channel.dart:1
E/flutter (17871): <asynchronous suspension>
Firebse Function :
exports.helloWorld = functions.https.onCall((data, context) => {
return data.data()['uid'];
});
Flutter run function from Firebase :
IconButton(
icon: Icon(Icons.add),
onPressed: () async {
HttpsCallable callable =
FirebaseFunctions.instance.httpsCallable('listFruit');
final results = await callable.call(<String, dynamic>{
'uid': '123',
});
print(results
.data.toString()); // ["Apple", "Banana", "Cherry", "Date", "Fig", "Grapes"]
});
My goal :
pass parameters to firebase function .
I had the same error and it was due to the fact that the region was not provided, which seems to be required if the function is not deployed in us-central1. Following their documentation, you can perform the call like this:
FirebaseFunctions.instanceFor(region: 'europe-west1').httpsCallable('listFruit');
Instead of
exports.helloWorld = functions.https.onCall((data, context) => {
return data.data()['uid'];
});
you should do
exports.helloWorld = functions.https.onCall((data, context) => {
return data['uid']; // Or data.uid
});
Few more details in the Callable Cloud Functions doc.
In addition, note that your Cloud Function is named helloWorld but you call it with FirebaseFunctions.instance.httpsCallable('listFruit');. So you should adapt one or the other, e.g. FirebaseFunctions.instance.httpsCallable('helloWorld');

Resources