title: Unhandled Exception: Bad state: Cannot add new events after calling close?
body: <p>I'm making a login feature, I'm making fire responses to find out whether responses were successful or failed. can see my BLOC coding. the login process was successful but when I want to return to the login page after logging out the error appears Unhandled Exception: Bad state: Cannot add new events after calling close. how can I handle it?</p>
  
  <p>API RESPONSES :</p>
  
  <pre><code>class ApiResponse&lt;T&gt; {
    Status status;
    T data;
    String message;
  
    ApiResponse.loading(this.message) : status = Status.LOADING;
  
    ApiResponse.completed(this.data) : status = Status.COMPLETED;
  
    ApiResponse.error(this.message) : status = Status.ERROR;
  
  //  @override
  //  String toString() {
  //    return "Status : $status \n Message : $message \n Data : $data";
  //  }
  }
  
  enum Status { LOADING, COMPLETED, ERROR }
  </code></pre>
  
  <p>BLOC :</p>
  
  <pre><code>class LoginBloc extends Object with Validators{
    final _repository = EresidenceRepository();
    final _userid = BehaviorSubject&lt;String&gt;();
    final _password = BehaviorSubject&lt;String&gt;();
    final _imei = BehaviorSubject&lt;String&gt;();
    final _coordinate = BehaviorSubject&lt;String&gt;();
    final BehaviorSubject&lt;ApiResponse&lt;login_responses&gt;&gt; _subject = BehaviorSubject&lt;ApiResponse&lt;login_responses&gt;&gt;();
  
    Function(String) get userid =&gt; _userid.sink.add;
    Function(String) get password =&gt; _password.sink.add;
    Function(String) get imei =&gt; _imei.sink.add;
    Function(String) get coordinate =&gt; _coordinate.sink.add;
  
    Stream&lt;String&gt; get useridValidation =&gt; _userid.stream.transform(useridValidator);
    Stream&lt;String&gt; get passwordValidation =&gt; _password.stream.transform(passwordValidator);
    Stream&lt;bool&gt; get submitCheck =&gt; Rx.combineLatest2(useridValidation, passwordValidation, (e,p) =&gt; true);
  
    login() async {
      _subject.sink.add(ApiResponse.loading("Logging In..."));
      try {
        login_responses response = await _repository.login(
            _userid.value, _password.value, _imei.value, _coordinate.value);
  
        prefsBloc.changePrefsLogin(
            PrefsState(false, response.data.userid, response.data.password, _imei.value, _coordinate.value, "")
        );
  
        _subject.sink.add(ApiResponse.completed(response));
  
        print(response);
  
      } catch (e) {
        _subject.sink.add(ApiResponse.error(e.toString()));
        print(e);
      }
    }
  
    dispose(){
      _userid.close();
      _password.close();
      _imei.close();
      _coordinate.close();
      _subject.close();
    }
  
    BehaviorSubject&lt;ApiResponse&lt;login_responses&gt;&gt; get subject =&gt; _subject;
  
  }
  
  final login = LoginBloc();
  </code></pre>
  
  <p>UI :</p>
  
  <pre><code>class LoginPage extends StatefulWidget {
    @override
    _LoginPageState createState() =&gt; _LoginPageState();
  }
  
  class _LoginPageState extends State&lt;LoginPage&gt; with WidgetsBindingObserver{
  
    final GlobalKey&lt;ScaffoldState&gt; _scaffoldKey = new GlobalKey&lt;ScaffoldState&gt;();
    FocusNode passwordFocusNode, useridFocusNode;
  
    @override
    void initState() {
      super.initState();
  
      prefsBloc.checkLoginPref(context);
  
  
      WidgetsBinding.instance.addObserver(this);
    }
  
    @override
    void dispose() {
  
      WidgetsBinding.instance.removeObserver(this);
      super.dispose();
    }
  
  
    @override
    Widget build(BuildContext context) {
      return AnnotatedRegion&lt;SystemUiOverlayStyle&gt;(
          value: SystemUiOverlayStyle.dark,
          child: Scaffold(
            backgroundColor: Colors.white,
            body: StreamBuilder(
                stream: login.subject,
                builder: (context, AsyncSnapshot&lt;ApiResponse&lt;login_responses&gt;&gt; snapshot){
                  if(snapshot.hasData) {
                    print(snapshot.data.status);
                    switch (snapshot.data.status) {
                      case Status.LOADING:
                        _onWidgetDidBuild((){
                          Scaffold.of(context).showSnackBar(
                              SnackBar(
                                content: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(snapshot.data.message),
                                    CircularProgressIndicator(),
                                  ],
                                ),
                                backgroundColor: Colors.black,
                              ),
                            );
                        });
                        break;
                      case Status.COMPLETED:
                        login_responses result = snapshot.data.data;
                        if(result.data.bit70 == "000") {
                          _onWidgetDidBuild((){
                            login.dispose();
                            AppRoutes.replace(context, LoginVerifyPage());
                          });
                        }else{
                          _onWidgetDidBuild((){
                            login.dispose();
                            AppRoutes.replace(context, MainApp());
                          });
                        }
                        break;
                      case Status.ERROR:
                        _onWidgetDidBuild(() {
                          Scaffold.of(context).showSnackBar(SnackBar(
                            content: Text('${snapshot.data.message}'),
                            backgroundColor: Colors.red,
                          ));
                        });
                        break;
                    }
                  }
                  return _formLogin();
                }
            ),
          )
      );
    }
  
    _formLogin() {
      return SafeArea(
        child: Container(
          child: Column(
            children: &lt;Widget&gt;[
              Expanded(
                  flex: 1,
                  child: Container(
                      padding: EdgeInsets.symmetric(horizontal: SizeConfig.widthMultiplier * 1, vertical: SizeConfig.heightMultiplier * 1),
                      child: CachedNetworkImage(
                        imageUrl: "https://images.glints.com/unsafe/1024x0/glints-dashboard.s3.amazonaws.com/company-logo/68545821966f833d182f98775c73c7ae.png",
                        errorWidget: (context, url, error) =&gt; Icon(Icons.broken_image),
                        fit: BoxFit.fill,
                      ),
                  )
              ),
              Expanded(
                  flex: 2,
                  child: Container(
                      padding: EdgeInsets.all(SizeConfig.heightMultiplier * 2),
                      child: Column(
                        children: &lt;Widget&gt;[
                          Container(
                              child: StreamBuilder&lt;String&gt;(
                                stream: login.useridValidation,
                                builder: (context, snapshot) =&gt; DataTextField(
                                  errorText: snapshot.error,
                                  hintText: "No Handphone",
                                  textInputAction: TextInputAction.next,
                                  icon: Icons.phone,
                                  onSubmitted: () =&gt; FocusScope.of(context).requestFocus(passwordFocusNode),
                                  onChanged: login.userid,
                                  keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                                ),
                              )
                          ),
                          Container(
                              margin: EdgeInsets.only(top: SizeConfig.heightMultiplier * 2),
                              child: StreamBuilder&lt;String&gt;(
                                stream: login.passwordValidation,
                                builder: (context, snapshot) =&gt; PasswordTextField(
                                errorText: snapshot.error,
                                  hintText: "Password",
                                  textInputAction: TextInputAction.done,
                                  onSubmitted: () {
                                    FocusScope.of(context).requestFocus(FocusNode());
                                  },
                                  onChanged: login.password,
                                  focusNode: passwordFocusNode,
                                ),
                              )
                          ),
                          Container(
                              width: SizeConfig.screenWidth,
                              margin: EdgeInsets.only(top: SizeConfig.heightMultiplier * 2.5),
                              child: GestureDetector(
                                onTap: () =&gt; AppRoutes.push(context, ForgotPasswordPage()),
                                child: Text(
                                  Strings.titleForgotPass+" ?",
                                  style: AppTheme.styleSubTitlePurpel,
                                  textAlign: TextAlign.right,
                                ),
                              )
                          ),
                          Container(
                            width: SizeConfig.screenWidth,
                            margin: EdgeInsets.only(top: SizeConfig.heightMultiplier * 5),
                            child: StreamBuilder&lt;bool&gt;(
                              stream: login.submitCheck,
                              builder: (context, snapshot) =&gt; AppButton(
                                  onPressed: snapshot.hasData ? () =&gt; login.login() : null,
                                  text: Strings.signin
                              ),
                            )
                          )
                        ],
                      )
                  )
              ),
              Expanded(
                  flex: 1,
                  child: Container(
                      alignment: Alignment.bottomCenter,
                      margin: EdgeInsets.only(bottom: SizeConfig.heightMultiplier * 2.5),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: &lt;Widget&gt;[
                          Text(
                            Strings.dontAccount,
                            style: AppTheme.styleSubTitleBlackSmall,
                            textAlign: TextAlign.right,
                          ),
                          Container(
                              margin: EdgeInsets.only(left: SizeConfig.widthMultiplier * 1),
                              child: InkWell(
                                onTap: () =&gt; AppRoutes.push(context, RegistrationPage()),
                                child: Text(
                                  Strings.registration,
                                  style: AppTheme.styleSubTitlePurpel,
                                  textAlign: TextAlign.right,
                                ),
                              )
                          )
                        ],
                      )
                  )
              )
            ],
          ),
        ),
      );
    }
  
    void _onWidgetDidBuild(Function callback) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        callback();
      });
    }
  }
  </code></pre>