【问题标题】:when to dispose a bloc in flutter?什么时候在颤动中处理一个集团?
【发布时间】:2021-01-21 16:16:07
【问题描述】:

在下面的例子中,我们可以看到块是在这个有状态的小部件中新创建的

authenticationBloc = AuthenticationBloc(userRepository: userRepository);

class App extends StatefulWidget {
  final UserRepository userRepository;

  App({Key key, @required this.userRepository}) : super(key: key);

  @override
  State<App> createState() => _AppState();
}

class _AppState extends State<App> {
  AuthenticationBloc authenticationBloc;
  UserRepository get userRepository => widget.userRepository;

  @override
  void initState() {
    authenticationBloc = AuthenticationBloc(userRepository: userRepository); <------
    authenticationBloc.dispatch(AppStarted());
    super.initState();
  }

  @override
  void dispose() {                     <---------
    authenticationBloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<AuthenticationBloc>(
      bloc: authenticationBloc,
      child: MaterialApp(
        home: BlocBuilder<AuthenticationEvent, AuthenticationState>(
          bloc: authenticationBloc,
          builder: (BuildContext context, AuthenticationState state) {
            if (state is AuthenticationUninitialized) {
              return SplashPage();
            }
            if (state is AuthenticationAuthenticated) {
              return HomePage();
            }
            if (state is AuthenticationUnauthenticated) {
              return LoginPage(userRepository: userRepository);
            }
            if (state is AuthenticationLoading) {
              return LoadingIndicator();
            }
          },
        ),
      ),
    );
  }
}

但是它也被放置在同一个有状态的小部件中

 @override
  void dispose() {                     
    authenticationBloc.dispose(); <-----
    super.dispose();
  }

现在在子小部件HomePage() 中,如果authenticationBloc 已经在App statefulwidget 中处理,我怎么还能使用BlocProvider.of&lt;AuthenticationBloc&gt;(context) 访问它? authenticationBloc.dispose(); 不是正在关闭水槽吗?还是我理解错了?

【问题讨论】:

标签: flutter dart flutter-bloc


【解决方案1】:

当 _AppState 应该从树中永久删除并且 State 对象将永远不会再次构建时,将调用 dispose 方法。

因此,由于仍在构建子小部件,因此您的 dispose 方法尚未运行。

【讨论】:

  • 感谢您的回复,假设我在HomePage() 之后不再需要AuthenticationBloc,所以我可以在这里调用dispose() 方法对吗?如果我的homepage() 小部件是无状态的怎么办?在homepage() 中创建另一个有状态小部件只是为了调用 dispose 方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
相关资源
最近更新 更多