【发布时间】:2020-11-22 14:19:43
【问题描述】:
在下面的代码中, profileBloc 在 EditProfileScreenState 的 didChangeDependencies() 方法中初始化。
我们应该调用 EditProfileScreenState 类的 dispose 方法来处理 profileBloc 吗?
如果是这样,profileBloc方法应该如何处理,因为ProfileBloc类扩展了没有dispose方法的Bloc类?
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
}
}
}
【问题讨论】:
-
只有当您使用 BlocProvider 创建 bloc 时才会释放 bloc,并且在从小部件树中卸载 BlocProvider 时才会释放 bloc。希望有帮助
标签: flutter dart flutter-bloc