Reputation: 25070
I am working with flutter_bloc and trying to understand how it works entirely.
I have Profile Screen. Where in the User should enter his details if previously not existed else should update the details.
Logic: If the user already exists then i fill up the textfields prior to loading , else the textfields are left blank
Problem: I have worked out of achieving the above mentioned goal , but everything seems to work only the first time , Once i save the profile and come back to the profile page it doesn't load the data and textfields are empty even if the user exists.
User_Cubit
class UserCubit extends Cubit<UserState> {
UserCubit() : super(UserInitialState()) {
checkIfUserExists();
}
void checkIfUserExists() {
emit(UserLoadingState());
...
if (userExists) {
emit(UserExists(user));
} else {
emit(UserNotExists());
}
});
}
Profile Screen
class _MyProfileScreenState extends State<MyProfileScreen> {
TextEditingController? fullNameController;
TextEditingController? mailAddressController;
late UserCubit _userCubit;
@override
void initState() {
fullNameController = TextEditingController();
mailAddressController = TextEditingController();
_userCubit = UserCubit(); // initializing the cubit here
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: MultiBlocListener(
listeners: [
BlocListener<UserCubit, UserState>(
listener: (context, state) {
if (state is UserExists) {
appUser = state.user;
mailAddressController!.text = appUser!.email; // Loading the fields
fullNameController!.text = appUser!.fullName; // Loading the fields
}
},
)
],
child: BlocBuilder<UserCubit, UserState>(
builder: (context, state) {
if (state is UserLoadingState) {
return const Center(child: CircularProgressIndicator());
}
return Container(
TextFormField() // For fullName
TextFormField() // For EmailAddress
)
)
);
}
Why does this functionality work only the first time not the consecutive times. Thougth the UserCubit
is intialized in initstate
?
Any further suggestions to improve this logic by not initializing the UserCubit on every page render would be also appreciated !!
Upvotes: 3
Views: 879