放置在 flutter bloc 中

ana*_*edi 8 dart flutter flutter-bloc

在下面的代码中,profileBloc 在 EditProfileScreenState 的 didChangeDependency() 方法中初始化。

我们应该在 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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ana*_*edi 12

当我搜索时,我找到了解决方案。

我们不需要在 didChangeDependency() 中初始化 profileBloc。

我们可以使用以下方法直接从 BlocProvider 访问 add 方法:

BlocProvider.of<ProfileBloc>(context).add(ProfileSaved())
Run Code Online (Sandbox Code Playgroud)

我们可以从 EditProfileScreenState 类中删除以下部分。

ProfileBloc profileBloc;

  @override
  void didChangeDependencies() {
    profileBloc = BlocProvider.of<ProfileBloc>(context);
    super.didChangeDependencies();
  }
Run Code Online (Sandbox Code Playgroud)

此外,在 ProfileBloc 类中,我们可以使用 close 方法,以防我们需要取消任何流。

@override
  Future<void> close() {
    //cancel streams
    super.close();
  }
Run Code Online (Sandbox Code Playgroud)