Created a new class to manage sign-in methods in one place, a Dart class with no flutter Widget.
It gives errors about FIREBASE INITIALIZATION after following https://firebase.flutter.dev/docs/overview/#initializing-flutterfire.
Error: No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp().
_firebaseAuth is useless without it.
Full sample project here: https://github.com/dashanan13/time_tracker_flutter_course.git
Please help, this is frustrating.
StackTrace:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Running Gradle task 'assembleDebug'...
Parameter format not correct -
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Waiting for Android SDK built for x86 to report its views...
Debug service listening on ws://127.0.0.1:60201/mhWPMlMla50=/ws
Syncing files to device Android SDK built for x86...
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
W/AnalyticsUserIDStore(20120): initStore should have been called before calling setUserID
W/UserDataStore(20120): initStore should have been called before calling setUserID
D/EGL_emulation(20120): eglMakeCurrent: 0xd731a9c0: ver 2 0 (tinfo 0xd730f730)
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
I/OpenGLRenderer(20120): Davey! duration=2122ms; Flags=1, IntendedVsync=172506915033871, Vsync=172506948367203, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=172506964470903, AnimationStart=172506964518803, PerformTraversalsStart=172506964557703, DrawStart=172508239012703, SyncQueued=172508239844803, SyncStart=172508241475003, IssueDrawCommandsStart=172508241758403, SwapBuffers=172508678528903, FrameCompleted=172509039559203, DequeueBufferDuration=21745000, QueueBufferDuration=142000,
I/Choreographer(20120): Skipped 129 frames! The application may be doing too much work on its main thread.
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
I/asics_for_dars(20120): Background young concurrent copying GC freed 26775(1377KB) AllocSpace objects, 9(360KB) LOS objects, 41% free, 2468KB/4219KB, paused 131.474ms total 1.416s
D/EGL_emulation(20120): eglMakeCurrent: 0xea67f940: ver 2 0 (tinfo 0xd3e265e0)
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following FirebaseException was thrown building LandingPage(dirty, dependencies:
[InheritedProvider<AuthBase>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
LandingPage
file:///C:/Users/.../basics_for_darsh/lib/main.dart:68:41
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 Auth.onAuthStateChanged (package:basics_for_darsh/utilities/auth.dart:47:35)
#4 LandingPage.build (package:basics_for_darsh/utilities/landingPage.dart:18:22)
#5 StatelessElement.build (package:flutter/src/widgets/framework.dart:4620:28)
#6 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
#7 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
#8 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
#9 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
... Normal element mounting (132 frames)
#141 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#142 MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5991:32)
... Normal element mounting (287 frames)
#429 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
#430 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
#431 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1174:16)
#432 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1145:5)
#433 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1087:17)
#434 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2620:19)
#435 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1086:13)
#436 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:927:7)
#437 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:908:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
════════════════════════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following FirebaseException was thrown building LandingPage(dirty, dependencies: [InheritedProvider<AuthBase>]):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
The relevant error-causing widget was:
LandingPage file:///C:/Users/.../basics_for_darsh/lib/main.dart:68:41
When the exception was thrown, this was the stack:
#0 MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1 Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2 FirebaseAuth.instance (package:firebase_auth/src/firebase_auth.dart:37:47)
#3 Auth.onAuthStateChanged (package:basics_for_darsh/utilities/auth.dart:47:35)
#4 LandingPage.build (package:basics_for_darsh/utilities/landingPage.dart:18:22)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
E/GraphResponse(20120): {HttpStatus: 404, errorCode: 803, subErrorCode: -1, errorType: OAuthException, errorMessage: (#803) Cannot query users by their username (CHANGE-ME)}
Firebase authentication is useless without initialization.
Error: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()
Please help.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_facebook_login/flutter_facebook_login.dart';
import 'package:google_sign_in/google_sign_in.dart';
class MyUser {
MyUser({#required this.uid});
final String uid;
}
abstract class AuthBase {
Stream<MyUser> get onAuthStateChanged;
Future<MyUser> currentUser();
Future<MyUser> signInAnonymously();
Future<MyUser> signInWithGoogle();
Future<void> signOut();
}
class Auth implements AuthBase {
var _initialization,_firebaseAuth;
Auth(){
_intializeMe();
_firebaseAuth = FirebaseAuth.instance;
}
_intializeMe() async {
FirebaseApp _initialization = (await Firebase.initializeApp());
}
MyUser _userFromFirebase(User user) {
if (user == null) {
return null;
}
return MyUser(uid: user.uid);
}
#override
Stream<MyUser> get onAuthStateChanged {
return _firebaseAuth.authStateChanges().map(_userFromFirebase);
}
#override
Future<MyUser> currentUser() async {
final user = await _firebaseAuth.currentUser;
return _userFromFirebase(user);
}
#override
Future<MyUser> signInAnonymously() async {
final authResult = await _firebaseAuth.signInAnonymously();
return _userFromFirebase(authResult.user);
}
#override
Future<MyUser> signInWithGoogle() async {
final googleSignIn = GoogleSignIn();
final googleAccount = await googleSignIn.signIn();
if (googleAccount != null) {
final googleAuth = await googleAccount.authentication;
if (googleAuth.accessToken != null && googleAuth.idToken != null) {
final authResult = await _firebaseAuth.signInWithCredential(
GoogleAuthProvider.credential(
idToken: googleAuth.idToken,
accessToken: googleAuth.accessToken,
),
);
return _userFromFirebase(authResult.user);
} else {
throw PlatformException(
code: 'ERROR_MISSING_GOOGLE_AUTH_TOKEN',
message: 'Missing Google Auth Token',
);
}
} else {
throw PlatformException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user',
);
}
}
#override
Future<void> signOut() async {
final googleSignIn = GoogleSignIn();
await googleSignIn.signOut();
final facebookLogin = FacebookLogin();
await facebookLogin.logOut();
await _firebaseAuth.signOut();
}
}
Call for Auth() methods
import 'dart:async';
import 'package:basics_for_darsh/authentication/signin.dart';
import 'package:basics_for_darsh/screens/welcome_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'auth.dart';
class LandingPage extends StatelessWidget {
static const String id = 'landing_page';
#override
Widget build(BuildContext context) {
final auth = Provider.of<AuthBase>(context);
return StreamBuilder<MyUser>(
stream: auth.onAuthStateChanged,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
MyUser user = snapshot.data;
if (user == null) {
return AppSignIn();
}
return WelcomeScreen();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
});
}
}
initializeApp() is asynchronous, therefore do the following:
Auth(){
_intializeMe().then((_){
_firebaseAuth = FirebaseAuth.instance;
});
}
Future<void> _intializeMe() async {
return await Firebase.initializeApp();
}
Before accessing FirebaseAuth, you have to initialize Firebase. Therefore you can use then() which will register a callback that will be called when the future is done.
Related
I'm trying to create a flutter app with getx. Particularly in the authentication section, I have the following error:
E/flutter ( 8992): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: setState() called after dispose(): _LogButtonState#3e8d6(lifecycle state: defunct, not mounted)
E/flutter ( 8992): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 8992): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 8992): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 8992): #0 State.setState. (package:flutter/src/widgets/framework.dart:1085:9)
E/flutter ( 8992): #1 State.setState (package:flutter/src/widgets/framework.dart:1120:6)
E/flutter ( 8992): #2 _LogButtonState.build. (package:sneakychat/Screens/Authentication/login.dart:231:9)
E/flutter ( 8992):
E/flutter ( 8992):
The code for the authentication controller is the following:
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../Globals/globals.dart';
class AuthController extends GetxController {
final FirebaseAuth _auth = firebaseAuth;
late Rx<User?> _firebaseUser;
late Rx<GoogleSignInAccount?> _googleSignInAccount;
//UserModel get user => _firebaseUser.value;
late GoogleSignIn googleSignIn = GoogleSignIn();
//var a = googleSignIn.currentUser;
#override
onReady() {
super.onReady();
print("##########Im Reasdy###########");
googleSignIn = GoogleSignIn();
// Load current user
_firebaseUser = Rx<User?>(_auth.currentUser);
_googleSignInAccount = Rx<GoogleSignInAccount?>(googleSignIn.currentUser);
// Bind Streams for listeners
_firebaseUser.bindStream(_auth.userChanges());
_googleSignInAccount.bindStream(googleSignIn.onCurrentUserChanged);
// Call workers to update auth state
ever(_firebaseUser, _manageAuthState);
ever(_googleSignInAccount, _manageAuthStateGoogle);
}
// Manage the auth state
_manageAuthState(User? user) {
print("Firebase auth state active :D");
if (user == null) {
Get.offAllNamed("/LogIn");
} else {
Get.offAllNamed("/Home");
}
}
// Manage the auth state regarding google's user state
_manageAuthStateGoogle(GoogleSignInAccount? googleSignInAccount) {
print("Google auth state active");
if (googleSignInAccount == null) {
Get.offAllNamed("/LogIn");
} else {
Get.offAllNamed("/Home");
}
}
// Sign with google account
Future<void> signupGoogle() async {
final GoogleSignIn googleSignIn = GoogleSignIn();
try {
final GoogleSignInAccount? googleSignInAccount =
await googleSignIn.signIn();
_googleSignInAccount.value = googleSignInAccount;
if (googleSignInAccount != null) {
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
final AuthCredential authCredential = GoogleAuthProvider.credential(
idToken: googleSignInAuthentication.idToken,
accessToken: googleSignInAuthentication.accessToken);
// Bind Google account with Firebase account
UserCredential resultUser = await _auth.signInWithCredential(
authCredential);
print(resultUser.credential);
// Set a listener for the user
_firebaseUser.value = resultUser.user;
print(resultUser.user);
// Store user data if its new
/*User user = User(
name: username,
email: email,
uid: cred.user!.uid,
profilePhoto: downloadUrl,
);
await firestore
.collection('users')
.doc(cred.user!.uid)
.set(user.toJson());*/
Get.offAllNamed("/Home");
}
} catch (exc) {
print(exc);
Get.snackbar(
'Something went wrong',
"We couldn't connect with google's server",
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.amber,
colorText: Colors.white
);
}
}
Future<void> logoutGoogle() async {
print("Sign out!");
await googleSignIn.signOut();
await _auth.signOut();
print(googleSignIn.currentUser?.email);
print("#################################");
print(_firebaseUser.value?.uid);
print("#################################");
//Get.offAllNamed("/LogIn");
}
signIn() {}
}
You can stop listening to the animation in the dispose() callback or cancel the timer.
Another solution is to check the mounted property of the state class of your widget before calling setState().
For Example:
if (mounted) {
setState(() {
// Your code here
});
}
Dispose the worker on onClose().
So I have been trying to initialize my firebase with my flutter app but it keeps throwing an error every time, the code has no problem since flutter builds the app fine but just not firebase.
So this is my code to initialize firebase;
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _initialized = false;
bool _error = false;
void initializeFlutterFire() async {
try {
// Wait for Firebase to initialize and set `_initialized` state to true
await Firebase.initializeApp();
setState(() {
_initialized = true;
});
} catch (e) {
// Set `_error` state to true if Firebase initialization fails
setState(() {
_error = true;
});
}
}
#override
void initState() {
initializeFlutterFire();
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp();
and this is the error I keep getting:
Error: Assertion failed:
file:///home/pete/snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core_web-1.4.0/lib/src/fire
base_core_web.dart:271:11
options != null
"FirebaseOptions cannot be null when creating the default app."
at Object.throw_ [as throw] (http://localhost:35305/dart_sdk.js:5061:11)
at Object.assertFailed (http://localhost:35305/dart_sdk.js:4986:15)
at firebase_core_web.FirebaseCoreWeb.new.initializeApp
(http://localhost:35305/packages/firebase_core_web/firebase_core_web.dart.lib.js:243:42)
at initializeApp.next (<anonymous>)
at http://localhost:35305/dart_sdk.js:38640:33
at _RootZone.runUnary (http://localhost:35305/dart_sdk.js:38511:59)
at _FutureListener.thenAwait.handleValue (http://localhost:35305/dart_sdk.js:33713:29)
at handleValueCallback (http://localhost:35305/dart_sdk.js:34265:49)
at Function._propagateToListeners (http://localhost:35305/dart_sdk.js:34303:17)
at _Future.new.[_completeWithValue] (http://localhost:35305/dart_sdk.js:34151:23)
at async._AsyncCallbackEntry.new.callback (http://localhost:35305/dart_sdk.js:34172:35)
at Object._microtaskLoop (http://localhost:35305/dart_sdk.js:38778:13)
at _startMicrotaskLoop (http://localhost:35305/dart_sdk.js:38784:13)
at http://localhost:35305/dart_sdk.js:34519:9
I fixed the issue by the following steps:
Run flutter channel stable
Run flutter upgrade
replace await Firebase.initializeApp() with await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "AIzaSyD1C8QaEAxv9QJIm2DDF9N3_b3UZv5o",
appId: "1:270790104828:web:1da6b11a4729a7d79729",
messagingSenderId: "2707901048",
projectId: "todo-app-firebase-ce8",
),
);
replace the values with what you copied to index.html file when initializing web app on firebase console and copying the script code from there.
Restart the app.
Worked for me!
The firebase_options file is missing from your import statement and options is missing from the Firebase.initializeApp method.
Import the firebase_core plugin and firebase_options files.
//lib/main.dart
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Add options parameter to the Firebase.initializeApp method inside the main function.
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options:
DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
Documentation for FlutterFire - initializing-flutterfire
I was facing this issue so I just used this command and it was fixed. please try once before doing anything else
$ flutter upgrade
UPDATED:
Dont waste time on configuring it by yourself, use this CLI https://firebase.flutter.dev/docs/overview/#using-the-flutterfire-cli
Following the steps will lead you to configure it for all the platforms. Its MAGIC!
I want to compare the App's version manually through Firebase Firestore. In Firestore, I have a collection(system) with a document(update) with a field: newest_v_app = number 7. I want to access this field on a page in my app and want to compare it to a number. If the number in firestore is higher than the number in the app, I want a bool to set to true.
The Code I tried (to explain what I mean):
UpdatePage.dart
class UpdatePage extends StatefulWidget {
#override
_UpdatePageState createState() => _UpdatePageState();
}
class _UpdatePageState extends State<UpdatePage> {
bool update_available = false;
num current_version = 7;
dynamic newest_version_from_firebase = 7;
Future<dynamic> _getUpdateAvailable() async {
final DocumentReference document = FirebaseFirestore.instance.collection('system').doc('update');
print('Success GetUpdate 1');
await document.get().then<dynamic>((DocumentSnapshot snapshot) async {
setState(() {
newest_version_from_firebase = snapshot.data;
});
});
print('Success GetUpdate 2');
compareUpdate(context);
print('Success GetUpdate 3');
testUpdateComparer();
}
void compareUpdate(BuildContext context) {
if (newest_version_from_firebase > current_version) {
setState(() {
update_available = true;
});
} else {
setState(() {
update_available = false;
});
}
}
void testUpdateComparer() {
if (update_available == true) {
print('Success AvailableBool');
} else {
print('No AvailableBool');
}
}
#override
void initState() {
super.initState();
print('Success Init');
_getUpdateAvailable();
}
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return Scaffold(
);
}
}
Console & Error:
I/flutter (15814): Success Init
I/flutter (15814): Success GetUpdate 1
W/DynamiteModule(15814): Local module descriptor class for providerinstaller not found.
I/DynamiteModule(15814): Considering local module providerinstaller:0 and remote module providerinstaller:0
W/ProviderInstaller(15814): Failed to load providerinstaller module: No acceptable module found. Local version is 0 and remote version is 0.
I/flutter (15814): Success GetUpdate 2
I/flutter (15814): No AvailableBool
E/flutter (15814): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: NoSuchMethodError: Closure call with mismatched arguments: function '>'
E/flutter (15814): Receiver: Closure: () => Map<String, dynamic>? from Function 'data':.
E/flutter (15814): Tried calling: >(7)
E/flutter (15814): Found: >() => Map<String, dynamic>?
E/flutter (15814): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:63:5)
E/flutter (15814): #1 _UpdatePageState.compareUpdate (package:myapp/UpdatePage/UpdatePage.dart:44:38)
E/flutter (15814): #2 _UpdatePageState._getUpdateAvailable (package:myapp/UpdatePage/UpdatePage.dart:38:5)
E/flutter (15814): <asynchronous suspension>
E/flutter (15814):
Flutter 2.3.0-17.0.pre.19 • channel master • https://github.com/flutter/flutter.git
Framework • revision bcf05f4587 (4 months ago) • 2021-05-23 02:19:02 -0400
Engine • revision 8cd4cf0a67
Tools • Dart 2.14.0 (build 2.14.0-143.0.dev)
The snapshot.data returns a Map<String, dynamic> from firestore and you're trying to assign it to the variable newest_version_from_firebase that you're trying to use as a number, which is not possible.
snaposhot.data returns a Document in which your have your version number probably stored as a key value pair, like: {"versionNumber": 7}
to access it your should do, for example:
newest_version_from_firebase = snapshot.data["versionNumber"] as int;
Solved it:
Changed num to int
late DocumentSnapshot snapshot;
int current_version = 7;
int newest_version_from_firebase = 7;
void getUpdateAvailable() async {
final data = await FirebaseFirestore.instance.collection("system").doc("update").get() as DocumentSnapshot;
snapshot = data as DocumentSnapshot;
setState(() {
newest_version_from_firebase = snapshot["newest_version"] as int;
});
print(newest_version_from_firebase.toString());
compareUpdate(context);
}
I am trying to implement notifications for my app, but when initializing notifications FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message))gives the following error. I have looked through this issue and this issue and have taken the function myBackgroundMessageHandler that I'm using as an argument outside the class but the error still persists.
Below is the error:
E/flutter (10115): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: Null check operator used on a null value
E/flutter (10115): #0
MethodChannelFirebaseMessaging.registerBackgroundMessageHandler
(package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:179:53)
E/flutter (10115): #1
FirebaseMessagingPlatform.onBackgroundMessage=
(package:firebase_messaging_platform_interface/src/platform_interface/platform_interface_messaging.dart:101:16)
E/flutter (10115): #2 FirebaseMessaging.onBackgroundMessage
(package:firebase_messaging/src/messaging.dart:83:31) E/flutter
(10115): #3 main (package:okepos/main.dart:130:21) E/flutter
(10115):
Below is my code:
Future<dynamic> myBackgroundMessageHandler(RemoteMessage message) {
print('backgroundMessage: message => ${message.toString()}');
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FirebaseMessaging.onBackgroundMessage((message) => myBackgroundMessageHandler(message));
}
You might want to try and write your main function the following way. It might be that you need to initialize Firebase if you want to run your function in the background.
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}');
if (message.notification != null) {
print(message.notification.title);
print(message.notification.body);
}
// Create a notification for this
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
// Background Message Handler
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}
If you would like to see my implementation of Firebase Messaging with Flutter, check my github repo.
Today i updated the android emulator i use frecuently and for some reason im getting this error. I already update all possible dependences and packages.
I/FirebaseAuth(11346): [FirebaseAuth:] Preparing to create service connection to fallback implementation
W/System (11346): Ignoring header X-Firebase-Locale because its value was null.
E/flutter (11346): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: The getter 'user' was called on null.
E/flutter (11346): Receiver: null
E/flutter (11346): Tried calling: user
E/flutter (11346): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (11346): #1 _RegistrarseState.signupNewUser (package:mundoplay/code/registrarse/registrarse.dart:511:9)
E/flutter (11346): <asynchronous suspension>
This is part of my current code for the user to register:
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
void signupNewUser(BuildContext context) async {
showDialog(context: context,
barrierDismissible: false,
builder: (BuildContext context)
{
return barraProgreso(mensaje: "Creando su cuenta, espere...",);
});
final firebaseUser = (await _firebaseAuth
.createUserWithEmailAndPassword(
email: email.text, password: password.text)
.catchError((errMsg) {
Navigator.pop(context);
setState(() {
_error = Errors.show(errMsg.code);
});
})).user;
if (firebaseUser != null)
{
Map userDataMap = {
"nombre": nombre.text.trim(),
"apellido": apellido.text.trim(),
"email": email.text.trim(),
"password": password.text.trim(),
"celular": celular.text.trim(),
"direccion": direccion.text.trim(),
"localidad": localidad.text.trim(),
};
usersRef.child(firebaseUser.uid).set(userDataMap).then((value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('email', email.text);
//Navigator.push(context, new MaterialPageRoute(builder: (context) => new SeleccionarConsola()));
});
My register and login works with a form with TextEditingControllers that are set to the controller value.
I'm working with the firebase realtime database... any extra info, just ask me and i will try add it. THANKS!
According to the docs, catchError
Returns a new Future that will be completed with either the result of this future or the result of calling the onError callback.
So when you initialize your firebaseUser, you use a catchError that doesn't return nothing (i.e. implicitely returns null). You can see this in practice with a simple example:
Future<T> handleError<T>(Future<T> future) {
return future.catchError((e) {
print("An error occurred.");
// Not returning anything here!
});
}
void main() async {
// When no error occurs, it will print 1
print(await handleError(Future.value(1)));
// When an error occurs, it will print null
print(await handleError(Future.error(Error())));
}
Since you've already said that you're not connected to the internet since you're using an emulator, an error is being thrown inside the future (maybe a "no internet exception" kind of error), the future is returning null and thus the "The getter 'user' was called on null." message.
There are two ways you can avoid this:
Using the ?. operator:
final firebaseUser = (await _firebaseAuth
.createUserWithEmailAndPassword(
email: email.text, password: password.text)
.catchError((errMsg) {
Navigator.pop(context);
setState(() {
_error = Errors.show(errMsg.code);
});
}))?.user; // <- use it here!
Doing it step-by-step:
final result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email.text,
password: password.text,
).catchError((e) {
Navigator.pop(context);
setState(() => _error = Errors.show(errMsg.code));
});
// Early exit
if (result == null) return;
// Only retrieve the firebase user here
final firebaseUser = result.user;