when to dispose a bloc in flutter?

2.8k views Asked by At

In the below example we can see that the bloc is newly created in this stateful widget

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();
            }
          },
        ),
      ),
    );
  }
}

But then it is also being disposed in the same stateful widget

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

Now in the child widget HomePage(), How come I am still able to access the authenticationBloc using BlocProvider.of<AuthenticationBloc>(context) if it is already disposed in the App statefulwidget? Isn't authenticationBloc.dispose(); is closing the sink? or am I understanding this wrong?

1

There are 1 answers

1
Robert Sandberg On

The dispose method is called when the _AppState should be permanently removed from the tree and the State object will never be built again.

So your dispose method hasn't been run since child widgets are is still being built.