Flutter integration test Binding Error - overrode FlutterError.onError - integration-testing

I tried to create a test for my flutter app with integration_test. There is some error when i tried to run the test. Here's the error on the terminal:
'package:flutter_test/src/binding.dart': Failed assertion: line 810 pos 14: '_pendingExceptionDetails != null': A test overrode FlutterError.onError but either fail
ed to return it to its original state, or had unexpected additional errors that it could not handle. Typically, this is caused by using expect() before restoring Flut
terError.onError.
Here's my code :
void main() {
testWidgets('Test_Login_Using_Robo', (tester) async {
app.main();
await tester.pump();
await tester.pumpAndSettle(const Duration(seconds: 5));
final phoneNumberLoginTextField = find.byKey(const Key('phoneNumberTextField'));
await tester.tap(phoneNumberLoginTextField);
expect(phoneNumberLoginTextField, findsOneWidget);
await tester.enterText(phoneNumberLoginTextField, '82220099611');
await tester.tap(find.byKey(const Key('loginButton')));
///Wait user for loggin in
await tester.pumpAndSettle(const Duration(seconds: 5));
///We Expect to see the otp Screen
expect(find.byType(OTPControllerScreen), findsOneWidget);
});
}
Which part is resulting this error ? how to fix this ? thanks before

Related

Flutter Provider update user data in firestore

I'm trying to refactor my code to reduce Firebase read operations. For this I'm using Sharedpreferences. The code is structured in such a way that there's a provider that take's care of the update process and saves the new values in shared preferences. Here is the code.
submit() async {
final User user = _auth.currentUser;
DocumentReference ref =
FirebaseFirestore.instance.collection('users').doc(user.uid);
final prefs = await SharedPreferences.getInstance();
try {
if (_image != null){
mediaurl= await uploadImage();
await ref.update({"MediaURL": mediaurl});
prefs.setString("MediaURL", mediaurl);
}
if(username!=null){
ref.update({"username":userNamecontroller.text});
prefs.setString('username', username);
}
if(description!=null){
ref.update({"description":descriptionController.text});
prefs.setString('description', description);
}
} catch (e) {print("tHE ERROR IS $e");}
notifyListeners();
}
The problem however is the submit function does not work. No data is updated to firebase and the error from my catch block is
tHE ERROR IS NoSuchMethodError: The getter 'absolute' was called on null.
Any ideas what this 'absolute' is?

Login error when using firebase auth with flutter (firebase_auth/unknown)

I am getting an unknown error a few times when I try to log into my flutter app using my wi-fi network and some users (minority) also have difficulty logging in. The error :
E/flutter (20396): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception:
[firebase_auth/unknown] com.google.firebase.FirebaseException: An internal error has occurred.
[Failed to connect to www.googleapis.com/2800:3f0:4001:81f::200a:443]
But when I login using mobile network, it logs in normally, without error. Any idea how to solve this?
My login function:
Future<void> signIn(
{LocalUser user, Function onFail, Function onSucess}) async {
loading = true;
try {
final UserCredential authResult = await auth.signInWithEmailAndPassword(
email: user.email, password: user.password);
[...code]
} on FirebaseAuthException catch (e) {
loading = false;
onFail(getErrorString(e));
notifyListeners();
}
}
When you send a request to a server, it responds with a response (in the form of JSON). Flutter casts JSON file into a class in order to be able to work with it. When you aren't connected to the internet, there is no response. So Flutter can't cast a non-existent data to a class. As a result, an error is raised. One way of solving this is using try-catch.
try {
// Some Code that you expect to work
} catch (e) {
// Handle Unexpected Error
}

Initializing Firebase Throws an Error - Flutter

While I was trying to set up Firebase, I learned that I need to initialize Firebase after the last updates. But when I run:
Firebase.initializeApp();
I get an error saying:
_CastError (Null check operator used on a null value)
I tried to remove it, afterwords everything worked fine.
This is the code I am running:
Future<void> main() async {
await Firebase.initializeApp();
runApp(SignIn());
}
According to documents this is how you can initialize firebase in your app:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(); //Make sure you imported firebase_core
runApp(SignIn());
);
}
Happy Fluttering :)

Persistent log in using Firebase currentUser not working - Flutter app

My goal for this app is to have persistent log in, so that the user of my Flutter app needs to sign in only once (unless they sign out) and whenever my Flutter app restarts, they do not need to log back in. I saw many examples with using Firebase Authentication and the .currentUser() method, but I am still having to log in every time I restart the app. I have tested this on the simulator (ios) and on my physical iphone while running debug mode on xCode (usb connection). Is it possible that I cannot test this functionality this way? Because I do see a message pop up on both android studio and xCode terminals that mention lost connection to device or stopped running because of the restarting. If that's the case, how can I test that persistent log in is working?
If that isn't the case, what am I doing wrong?? I've included the code below. This is happening within a stateful widget, of course.
final _auth = FirebaseAuth.instance;
checkIfCurrentUserExists() async {
try {
await _auth.currentUser().then((user) {
print('this is the user $user');
if (user != null && user.email != null) {
userIsLoggedIn = true;
// this works fine!
}
});
} catch (e) {
print('current user was not found $e');
// this works fine!
}
}
// called inside initState()
setClientOnLoad() async {
await Spryte.checkIfCurrentUserExists();
var doesCurrentUserExist = userIsLoggedIn;
var currentUser = await returnCurrentUser();
if (doesCurrentUserExist == false) {
//if user is not authenticated, set anonymous user
// this works fine!
}
else {
//print('current user does exist');
await foo(currentUser.uid);
// 'foo' is meant to retrieve some data about the client on loading of the app
// so that the user doesn't have to log in every time the app restarts
// but for some reason it's not working for me
}
}
I have got the same problem. I was able to sign in but when restarting the app, I was getting another random UID.
It might sound stupid, but make sure you are not calling signInAnonymously(); at any point in your app without checking if there is already a current user.
This was my problem, I was always signing in anonymously at every app restart.
Here is what I did from my starting app page (which takes care of setting up the app including the user):
Future<FirebaseUser> signInAnonymously() async {
AuthResult result = await _auth.signInAnonymously();
final FirebaseUser user = result.user;
assert(user != null);
assert(await user.getIdToken() != null);
return user;
}
And here is the checking method:
Future<FirebaseUser> tryToFetchUser() async {
var user = await _auth.currentUser();
if (user == null) {
user = await FirebaseAuth.instance.onAuthStateChanged.first;
}
if (user == null) {
user = await signInAnonymously();
}
return Future.value(user);
}
I hope it will help some of you and avoid wasting time on stupid mistakes as I did!
You r calling setClientOnLoad() which is async inside init() method & other app navigation depends on this method so u need wrap all your async stuff in FutureBuilder().
if not then build() method ll be called before complete execution of setClientOnLoad()
e.g. :-
FutureBuilder(
future: setClientOnLoad(),
builder: (context, AsyncSnapshot<R> snapshot) {
if (snapshot.data == null) {
return Center(child: CircularProgressIndicator());
}
// after executing method completely
},
);

I'm getting an error NoSuchMethodError: The method currentUser was called on null.FLUTTER

I'm trying to check whether the user is signed in or not, I've authenticated my flutter app with firebase, I want the status of the user to redirect the app to either login page or home page, but I can't run the app it shows the error on red screen and the error is:
NoSuchMethodError: The method 'currentUser' was called on null.
Receiver: null
Tried calling: currentUser()
I saw the solution here
but I did not understood it properly
currentUser function:
Future<String> currentUser() async {
FirebaseUser user = await _firebaseAuth.currentUser();
return user!= null ? user.uid : null;
}
checking the authentication status:
void initState() {
super.initState();
try {
widget.auth.currentUser().then((userId) {
setState(() {
authStatus =
userId == null ? AuthStatus.notsignedIn : AuthStatus.signedIn;
});
});
} catch (e) {}
}
The error just means that your _firebaseAuth object is null. Try using
FirebaseUser user = await FirebaseAuth.instance.currentUser();

Resources