Flutter : black screen using stream controller

112 Views Asked by At

I am creating e-commerce app using MVVM architecture where I am using Stream Controller in ViewModel Class. When I change the orientation of my phone screen it says

Bad state: Stream has already been listened to

I have tried the adding the .broadcast When I initialize the stream controller

final StreamController _streamController = StreamController<ViewObject>.broadcast();

But still the output is not as desired instead the screen becomes blank.

1

There are 1 best solutions below

1
Mobin Ansar On

To fix this issue, you can cancel the stream subscription when the ViewModel class is disposed. You can do this by overriding the dispose method in your ViewModel class and calling the cancel method on the stream subscription. Here is an example

class MyViewModel extends ChangeNotifier {
  final StreamController _streamController = StreamController<ViewObject>.broadcast();
  Stream<ViewObject> get myStream => _streamController.stream;

  MyViewModel() {
    // Add data to the stream controller
    _streamController.add(myData);
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }
}