Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter: Unhandled Exception: Bad state: Cannot add new events after calling close

Tags:

flutter

dart

bloc

I am trying to use the bloc pattern to manage data from an API and show them in my widget. I am able to fetch data from API and process it and show it, but I am using a bottom navigation bar and when I change tab and go to my previous tab, it returns this error:

Unhandled Exception: Bad state: Cannot add new events after calling close.

I know it is because I am closing the stream and then trying to add to it, but I do not know how to fix it because not disposing the publishsubject will result in memory leak. here is my Ui code:

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  void initState() {
    serviceBloc.getAllServices();
    super.initState();
  }

  @override
  void dispose() {
    serviceBloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: serviceBloc.allServices,
      builder: (context, AsyncSnapshot<ServiceModel> snapshot) {
        if (snapshot.hasData) {
          return _homeBody(context, snapshot);
        }
        if (snapshot.hasError) {
          return Center(
            child: Text('Failed to load data'),
          );
        }
        return CircularProgressIndicator();
      },
    );
  }
}

_homeBody(BuildContext context, AsyncSnapshot<ServiceModel> snapshot) {
  return Stack(
      Padding(
          padding: EdgeInsets.only(top: screenAwareSize(400, context)),
          child: _buildCategories(context, snapshot))
    ],
  );
}

_buildCategories(BuildContext context, AsyncSnapshot<ServiceModel> snapshot) {
  return Padding(
    padding: EdgeInsets.symmetric(vertical: 20),
    child: GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3, crossAxisSpacing: 3.0),
      itemCount: snapshot.data.result.length,
      itemBuilder: (BuildContext context, int index) {
        return InkWell(
          child: CategoryWidget(
            title: snapshot.data.result[index].name,
            icon: Icons.phone_iphone,
          ),
          onTap: () {},
        );
      },
    ),
  );
}

here is my bloc code:

class ServiceBloc extends MainBloc {
  final _repo = new Repo();
  final PublishSubject<ServiceModel> _serviceController =
      new PublishSubject<ServiceModel>();
  Observable<ServiceModel> get allServices => _serviceController.stream;
  getAllServices() async {
    appIsLoading();
    ServiceModel movieItem = await _repo.getAllServices();
    _serviceController.sink.add(movieItem);
    appIsNotLoading();
  }

  void dispose() {
    _serviceController.close();
  }
}

ServiceBloc serviceBloc = new ServiceBloc();

I did not include the repo and API code because it is not in the subject of this error.

like image 396
geekymano Avatar asked Apr 05 '19 13:04

geekymano


3 Answers

Use StreamController.isClosed to check if the controller is closed or not, if not closed add data to it.

if (!_controller.isClosed) 
  _controller.sink.add(...); // safe to add data as _controller isn't closed yet

From Docs:

Whether the stream controller is closed for adding more events.

The controller becomes closed by calling the close method. New events cannot be added, by calling add or addError, to a closed controller.

If the controller is closed, the "done" event might not have been delivered yet, but it has been scheduled, and it is too late to add more events.

like image 140
CopsOnRoad Avatar answered Nov 03 '22 17:11

CopsOnRoad


If the error is actually caused by the code you posted, I'd just add a check to ensure no new events are added after dispose() was called.

class ServiceBloc extends MainBloc {
  final _repo = new Repo();
  final PublishSubject<ServiceModel> _serviceController =
      new PublishSubject<ServiceModel>();
  Observable<ServiceModel> get allServices => _serviceController.stream;
  getAllServices() async {
    // do nothing if already disposed
    if(_isDisposed) {
      return;
    }
    appIsLoading();
    ServiceModel movieItem = await _repo.getAllServices();
    _serviceController.sink.add(movieItem);
    appIsNotLoading();
  }

  bool _isDisposed = false;
  void dispose() {
    _serviceController.close();
    _isDisposed = true;
  }
}

ServiceBloc serviceBloc = new ServiceBloc();
like image 20
Günter Zöchbauer Avatar answered Nov 03 '22 17:11

Günter Zöchbauer


I run into same error and noticed that if you check isClosed, the screen is not updated. In your code you have to remove the last line from Bloc file:

ServiceBloc serviceBloc = new ServiceBloc();

and put this line in CategoryPage just before the initState(). This way your widget is creating and disposing the bloc. Before, the widget only disposes the bloc but it is never re-created when the widget is re-created.

like image 3
cwhisperer Avatar answered Nov 03 '22 18:11

cwhisperer