Flutter auth firebase getx setstate() called after dispose - firebase

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().

Related

The getter 'user' was called on null on a Firebase Realtime Database + Flutter App

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;

Flutter & Firebase - Apple Sign In not working

I am trying to set up with apple sign in with the following code. When tapping the button nothing happens.
I get the following error:
Tried calling: authorizationCode
flutter: NoSuchMethodError: The getter 'authorizationCode' was called on null.
Receiver: null
How would I fix this?
Future<bool> get appleSignInAvailable => AppleSignIn.isAvailable();
Future<User> appleSignIn() async {
try {
final AuthorizationResult appleResult =
await AppleSignIn.performRequests([
AppleIdRequest(requestedScopes: [Scope.email, Scope.fullName])
]);
if (appleResult.error != null) {
// handle errors from Apple
}
final AuthCredential credential =
OAuthProvider('apple.com').credential(
accessToken:
String.fromCharCodes(appleResult.credential.authorizationCode),
idToken: String.fromCharCodes(appleResult.credential.identityToken),
);
UserCredential result =
await Global.fbAuth.signInWithCredential(credential);
User user = result.user;
updateUserData(user);
return user;
} catch (error) {
print(error);
return null;
}
}
If you are using iOS 14 simulator, this may be due to the issue reported here. The workaround would be to use a real device for debugging or use the iOS 13 simulator
Also, see this thread for reference
I have faced same kind of issue in one of my projects.You have to add your sha key in firebase and facebook to resolve the issue.
Also you can try the below code,
import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/services.dart';
class AuthService {
final _firebaseAuth = FirebaseAuth.instance;
Future<User> signInWithApple({List<Scope> scopes = const []}) async {
// 1. perform the sign-in request
final result = await AppleSignIn.performRequests(
[AppleIdRequest(requestedScopes: scopes)]);
// 2. check the result
switch (result.status) {
case AuthorizationStatus.authorized:
final appleIdCredential = result.credential;
final oAuthProvider = OAuthProvider('apple.com');
final credential = oAuthProvider.credential(
idToken: String.fromCharCodes(appleIdCredential.identityToken),
accessToken:
String.fromCharCodes(appleIdCredential.authorizationCode),
);
final authResult = await _firebaseAuth.signInWithCredential(credential);
final firebaseUser = authResult.user;
if (scopes.contains(Scope.fullName)) {
final displayName =
'${appleIdCredential.fullName.givenName} ${appleIdCredential.fullName.familyName}';
await firebaseUser.updateProfile(displayName: displayName);
}
return firebaseUser;
case AuthorizationStatus.error:
throw PlatformException(
code: 'ERROR_AUTHORIZATION_DENIED',
message: result.error.toString(),
);
case AuthorizationStatus.cancelled:
throw PlatformException(
code: 'ERROR_ABORTED_BY_USER',
message: 'Sign in aborted by user',
);
default:
throw UnimplementedError();
}
}
}

Flutter: Unable to Firebase.initializeApp() Firebase authentication services

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.

UserCredential in Firebase

I'm having an error with Firebase for the first time, and not sure why it keeps showing the error.
Error :
The name 'UserCredential' is defined in the libraries 'package:firebase/src/auth.dart (via package:firebase/firebase.dart)' and 'package:firebase_auth/firebase_auth.dart'.\nTry using 'as prefix' for one of the import directives, or hiding the name from all but one of the imports.
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Create user object based on FirebaseUser
CustomUsers _customModelForFirebaseUser(user) {
return user != null ? CustomUsers(uid: user.uid) : null;
}
// auth changed user stream
Stream<CustomUsers> get user {
return _auth.authStateChanges().map(_customModelForFirebaseUser);
}
//Signin Anon
Future signInAnon() async {
try {
UserCredential userCredential = await _auth.signInAnonymously();
CustomUsers user = userCredential.user;
print(_customModelForFirebaseUser(user));
} catch (e) {
print(e.toString());
return null;
}
}
The package have same class name, which causing packing to conflicts. Try to hide one of them like this
import 'package:firebase_auth/firebase_auth.dart' hide UserCredential;
For more explanation check out this webiste dart-flutter-how-to-solve-naming-conflict-or-ambiguous

How can I access the Firebase Flutter plugin from a test?

I want to run the real Firebase (not a mock) during a Flutter test. I'm trying to authenticate Firebase with FirebaseOptions:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import "package:test/test.dart";
Future<void> main() async {
final FirebaseApp app = await FirebaseApp.configure(
name: 'test',
options: const FirebaseOptions(
googleAppID: 'xxxxxxx',
projectID: 'yyyyyy',
),
);
final Firestore firestore = Firestore(app: app);
await firestore.settings(timestampsInSnapshotsEnabled: true);
test('Testing access.', () async {
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.signInAnonymously();
firestore.collection('aaaaa').document('bbbbb').get().then((documentSnaphot) {
expect(documentSnaphot['xxxx'], 'ccccc');
});
});
}
However, I'm getting the following error:
Failed to load "C:\Users\Ed\testing\app\test\user_test.dart":
MissingPluginException(No implementation found for method
FirebaseApp#appNamed on channel plugins.flutter.io/firebase_core)
package:flutter/src/services/platform_channel.dart 278:7
MethodChannel.invokeMethod
===== asynchronous gap ===========================
c: 38:53
FirebaseApp.appNamed
===== asynchronous gap ===========================
c: 64:55
FirebaseApp.configure
===== asynchronous gap ===========================
test\usuario_test.dart 7:45
main
===== asynchronous gap ===========================
package:test
serializeSuite
..\..\..\AppData\Local\Temp\flutter_test_listener.64a30b51-eb69-11e8-
a427-1831bf4c06e8\listener.dart 19:27 main
How can I solve this?
Plugins run only on mobile devices (or emulators).
To make testing code that uses plugins possible, you can register your own handlers that respond to method channel requests like the native side of plugins would
test('gets greeting from platform', () async {
const channel = MethodChannel('foo');
channel.setMockMethodCallHandler((MethodCall call) async {
if (call.method == 'bar')
return 'Hello, ${call.arguments}';
throw MissingPluginException();
});
expect(await hello('world'), 'Platform says: Hello, world');
});
From the last section of https://medium.com/flutter-io/flutter-platform-channels-ce7f540a104e
This will check the current firebase user null or not. Still I'm writing the tests. Will update a test for signInAnonymously if possible.
test('API current Firebase user', () async {
MethodChannel channel = MethodChannel(
'plugins.flutter.io/firebase_auth',
);
channel.setMockMethodCallHandler((MethodCall call) async {
if (call.method == 'currentUser') {
return ;
}
;
throw MissingPluginException();
});
FirebaseUser user = await FirebaseAuth.instance.currentUser();
expect(user, null);
});

Resources