try {
final result = await http.get(pingUrl)
.catchError((e) => print(e));
return result;
} catch (e) {
print(e)
}
but I got this:
Why I can't handle exception here in catch block?
No, because you are catching in Future.
You shouldn't cath in future:
try {
final result = await http.get(pingUrl);
// .catchError((e) => print(e)); <- removed
return result;
} catch (e) {
print(e)
}
Or throw again in catchError:
try {
final result = await http.get(pingUrl)
.catchError((e) {
print(e);
throw foo;
});
return result;
} catch (e) {
print(e)
}
I prefer the first option.
Related
I have a file named todo_repository.dart and has readTodo() function. Whenever I print the data variable here, there are returned contents/values but after I passed the data to another file named todo_list_cubit.dart, the data returns null value.
Here is the readTodo() of todo_repository.dart
Future<dynamic> readTodo() async {
try {
final User user = auth.currentUser!;
final uid = user.uid;
await usersTodo.doc(uid).get().then((DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists) {
var data = documentSnapshot.data() as Map;
//The data here is not empty
print(data);
return data;
}
});
} on FirebaseException catch (e) {
throw CustomError(
code: e.code,
message: e.message!,
plugin: e.plugin,
);
} catch (e) {
throw CustomError(
code: 'Exception',
message: e.toString(),
plugin: 'flutter_error/server_error',
);
}
}
Here is the readTodo() of todo_list_cubit.dart
Future<void> readTodo() async {
try {
emit(state.copyWith(
todoListStatus: TodoListStatus.loading,
));
//Start - Part of code where I have issue
Map todoRepoRead = await todoRepository.readTodo();
**after I passed the data from todoRepository.readTodo(), the value returns null**
print(todoRepoRead);
//End - Part of code where I have issue
final rTodos = state.todos.map((Todo todo) {
return Todo(
id: todoRepoRead['id'],
description: todoRepoRead['description'],
completed: todoRepoRead['completed'],
);
}).toList();
emit(state.copyWith(
todoListStatus: TodoListStatus.loaded,
todos: rTodos,
));
} on CustomError catch (e) {
emit(state.copyWith(
todoListStatus: TodoListStatus.error,
error: e,
));
}
}
You should either use async/await or then, but not both.
Using just await, your code becomes:
Future<dynamic> readTodo() async {
try {
final User user = auth.currentUser!;
final uid = user.uid;
DocumentSnapshot documentSnapshot = await usersTodo.doc(uid).get();
if (documentSnapshot.exists) {
var data = documentSnapshot.data() as Map;
//The data here is not empty
print(data);
return data;
};
// TODO: you still need to return something here
} on FirebaseException catch (e) {
throw CustomError(
code: e.code,
message: e.message!,
plugin: e.plugin,
);
} catch (e) {
throw CustomError(
code: 'Exception',
message: e.toString(),
plugin: 'flutter_error/server_error',
);
}
}
In the last update of cloud_firestore, I get an error when I run the app with the old code. How can I convert a Stream<QuerySnapshot<Map<String, dynamic>>> to a List?
I have this code and I get null values:
Stream<List<Model>> getReviews(String id) {
try {
return _collectionReference.doc(id).collection('reviews').orderBy('date', descending: true).snapshots().map((reviews) => reviews.docs.map((review) => Model.fromJson(review.data())));
} catch (error) {
return error.message;
}
}
If you just want to get the List<Model> use a get call and await the result before returning the List<Model> like here:
Future<List<Model>> getReviews(String id) {
try {
QuerySnapshot querySnapshot=await _collectionReference.doc(id).collection('reviews').orderBy('date', descending: true).get();
List<Model> result;
querySnapshot.docs.forEach((doc) {
print(doc["first_name"]);
result.add(Model.fromJson(review.data()));
});
return result;
} catch (error) {
return error.message;
}
Make sure to call getReviews as asynchronous.
When using firebase auth and type not registered email,
although I used try - catch, that does not fire.
fAuth.signInWithEmailAndPassword definitely throw PlatformException but that code does not catch that.
I suffered this problem about 2days..... please help me
Future<bool> signInWithEmail(String email, String password) async {
try {
var result = await fAuth.signInWithEmailAndPassword(
email: email, password: password);
if (result != null) {
setUser(result.user);
FirebaseFirestore.instance.collection("User").doc(_user.uid).get().then((doc) {
info.set(
name: doc["name"],
email: doc["email"],
phoneNumber: doc["phoneNumber"],
follower: doc["follower"],
following: doc["following"],
like: doc["like"],
review: doc["review"],
visited: doc["visited"],
favorite: doc["favorite"],
);
print(doc['name']);
notifyListeners();
});
return true;
}
return false;
} on PlatformException catch (e) {
List<String> result = e.toString().split(", ");
setLastFBMessage(result[1]);
return false;
} on Exception catch (e) {
List<String> result = e.toString().split(", ");
setLastFBMessage(result[1]);
return false;
} catch (e) {
List<String> result = e.toString().split(", ");
setLastFBMessage(result[1]);
return false;
}
}
I have a big problem but I know it is small for humankind. I'm trying email and password Authentication on Firebase with Flutter.
But I always get some exceptions. (PlatformException and FirebaseAuthExceptions).
`
void signInUser(String email, String password) async {
try {
if (_auth.currentUser == null) {
User _oturumAcanUser = (await _auth.signInWithEmailAndPassword(
email: email, password: password))
.user;
Get.to(HomeScreen());
Get.snackbar("Oturum açıldı", "message");
} else {
Get.snackbar("Oturum zaten açık", "message");
Get.to(HomeScreen());
}
} on PlatformException catch (e) {
_error = e.message;
Get.snackbar("başlık", e.message);
throw e;
} catch (e) {
_error = e.toString();
Get.snackbar("başlık", e.message);
}
}
`
Also, I'm using the getX package. I tried everything but I can't catch the exceptions. When I call this method from UI, the SDK (VSCode) pausing debugging app and show exceptions in red alert.
I read a lot of documents about this situation but I couldn't found a solution.
void signInUser(String email, String password) async {
try {
if (_auth.currentUser == null) {
User _oturumAcanUser = (await _auth.signInWithEmailAndPassword(
email: email, password: password))
.user;
Get.off(HomeScreen());
Get.snackbar("Oturum açıldı", "message", backgroundColor: Colors.teal);
} else {
Get.off(HomeScreen());
}
} on FirebaseAuthException catch (e) {
_error = e.code;
Get.snackbar("Giriş Yapılırken Hata",
"Giriş ypaılırken hata ile karşılaşıldı. Kod: ${e.code}",
snackPosition: SnackPosition.BOTTOM, snackStyle: SnackStyle.FLOATING);
throw e;
} catch (e) {
_error = e.toString();
Get.snackbar("Hata",
"Sunucu beklenmedik bir hata ile karşılaştı. Detaylı bilgi: ${e.message}");
}
I just did something like this and solve my problem. Still I dont understand where is different catch things. Thanks for all help. <3
Ok, you can try to use the catch method after signInWithEmailAndPassword like this:
void signInUser(String email, String password) async {
try {
if (_auth.currentUser == null) {
User _oturumAcanUser = (await _auth.signInWithEmailAndPassword(
email: email, password: password)
// Here, you can handle the error!
.catchError((error) {
print("The error message is: ${error.message}");
Get.snackbar("başlık", error.message);
})
.user;
Get.to(HomeScreen());
Get.snackbar("Oturum açıldı", "message");
} else {
Get.snackbar("Oturum zaten açık", "message");
Get.to(HomeScreen());
}
} on PlatformException catch (e) {
_error = e.message;
Get.snackbar("başlık", e.message);
throw e;
} catch (e) {
_error = e.toString();
Get.snackbar("başlık", e.message);
}
}
The error I am receiving: Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The getter 'uid' was called on null.
Receiver: null
Tried calling: uid)
#override
AuthenticationState get initialState => Uninitialized();
#override
Stream<AuthenticationState> mapEventToState(
AuthenticationEvent event,
) async* {
if (event is AppStarted) {
yield* _mapAppStartedToState();
} else if (event is LoggedIn) {
yield* _mapLoggedInToState();
} else if (event is LoggedOut) {
yield* _mapLoggedOutToState();
}
}
Stream<AuthenticationState> _mapAppStartedToState() async* {
try {
final isSignedIn = await _userRepository.isSignedIn();
if (isSignedIn) {
final uid = await _userRepository.getUser();
final isFirstTime = await _userRepository.isFirstTime(uid);
if (!isFirstTime) {
yield AuthenticatedButNotSet(uid);
} else {
yield Authenticated(uid);
}
} else {
yield Unauthenticated();
}
} catch (_) {
yield Unauthenticated();
}
}
The error is happening when I call getUser, but im not sure why because I included a catch block that yields Unauthenticated
Future<String> getUser() async {
return (await _firebaseAuth.currentUser()).uid;
}