1

Here I'm using GetIt. I created a class contains stream and also mark this class as singleton, I created a widget that uses this stream. Problem is whenever I used this in multiple location it causes Bad state: Stream has already been listened to

Problem is

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            MaterialButton(
              onPressed: () {
                Dog().bark();
              },
              child: Text('Add'),
            ),
            Lopez(),
            Lopez(),
          ],
        ),
      ),
    );
  }
}

class Lopez extends StatelessWidget {
  const Lopez({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: StreamBuilder(
        stream: Dog().onBark,
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.active:
              {
                if (snapshot.hasData) {
                  return Text(snapshot.data.toString());
                }
              }
          }
        },
      ),
    );
  }
}

class Dog {
  var _barkController = StreamController();
  static Dog _dog = Dog._();
  factory Dog() {
    return _dog;
  }
  Dog._();
  Stream get onBark => _barkController.stream.asBroadcastStream();
  void bark() {
    _barkController.add("woof " + DateTime.now().toString());
  }
}

Created Singleton of Dog class. Dog Singleton's stream is used in a Widget named Lopez, when I used this widget twice first call works but remaining calls got Bad State Error.

enter image description here

Edit: Used TSR's example for recreation of problem.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
arunized
  • 38
  • 5

1 Answers1

0

Make the stream broadcast mode. This example will guide you

class Dog{  
  var _barkController = StreamController();
  Stream get onBark => _barkController.stream.asBroadcastStream();
  void bark(){
    _barkController.add("woof");
  }
}

TSR
  • 17,242
  • 27
  • 93
  • 197
  • Yes I did same. But got Bad State error while using same widget in multiple area. But no issues if I'm using it in only one area. – arunized Sep 11 '21 at 08:21