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,
));
}
}
CodePudding user response:
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',
);
}
}