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.
Edit: Used TSR's example for recreation of problem.