Reputation: 481
On the code below, profileBloc is initialized in EditProfileScreenState's didChangeDependencies() method.
Should we be calling dispose method on EditProfileScreenState class to dispose the profileBloc ?
If so , how should the profileBloc method be disposed as ProfileBloc class extends Bloc class which doesn't have dispose method?
class Profile extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (BuildContext context) => ProfileBloc(AuthRepo()),
child: ProfileScreen(),
);
}
}
class ProfileScreen extends StatefulWidget {
@override
EditProfileScreenState createState() => EditProfileScreenState();
}
class EditProfileScreenState extends State<ProfileScreen> {
ProfileBloc profileBloc;
@override
void didChangeDependencies() {
profileBloc = BlocProvider.of<ProfileBloc>(context);
super.didChangeDependencies();
}
@override
void dispose() {
// TODO: implement dispose
//profileBloc.dispose() cannot call as ProfileBloc class doesn't have dispose method
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: BlocConsumer<ProfileBloc, ProfileState>(
listener: (context, state) {
},
builder: (BuildContext context,ProfileState state) {
return RaisedButton(onPressed: ()=>profileBloc.add(SaveProfile("name","email")));
}
));
}
}
class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {
AuthRepo authRepo;
ProfileBloc(this.authRepo) : super(ProfileSaved());
@override
Stream<ProfileState> mapEventToState(ProfileEvent event) async* {
if (event is SaveProfile) {
//Actions
}
}
}
Upvotes: 9
Views: 21792
Reputation: 481
While I was searching, I found the solution.
We don't need to initialize the profileBloc in didChangeDependencies().
We can access the add method directly from the BlocProvider using:
BlocProvider.of<ProfileBloc>(context).add(ProfileSaved())
We can remove following section from EditProfileScreenState class.
ProfileBloc profileBloc;
@override
void didChangeDependencies() {
profileBloc = BlocProvider.of<ProfileBloc>(context);
super.didChangeDependencies();
}
Moreover, In ProfileBloc class we can use close method in case we need to cancel any streams.
@override
Future<void> close() {
//cancel streams
super.close();
}
Upvotes: 13