0

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?

Manas
  • 3,060
  • 4
  • 27
  • 55
  • please help me https://stackoverflow.com/questions/64797323/dispose-in-flutter-bloc-and-rxd – Jsoon Nov 12 '20 at 10:29

1 Answers1

0

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.

Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • Thank you for the reply, so let's say I no longer need the `AuthenticationBloc` after `HomePage()` so I can call the dispose() method here right? What if my `homepage()` widget is stateless? create another stateful widget in `homepage()` just to call the dispose method? – Manas Oct 08 '20 at 06:02