I have made a simple app using bloc
and InheritedWidget
.
Following is the code
class Bloc {
final StreamController<bool> _changeColor = PublishSubject<bool>();
Function(bool) get changeColour => _changeColor.sink.add;
Stream<bool> get colour => _changeColor.stream;
void dispose(){
_changeColor.close();
}
}
class Provider extends InheritedWidget {
final bloc = Bloc();
Provider({Key key,Widget child}): super(key: key,child: child);
@override
bool updateShouldNotify(InheritedWidget oldWidget) {
return true;
}
static Bloc of(BuildContext context){
return (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc;
}
void dispose(){
bloc?.dispose();
}
}
class _HomePageState extends State<HomePage> {
var bloc;
@override
void initState() {
super.initState();
bloc = Provider.of(context);
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RaisedButton(
onPressed: () {
bloc.changeColour(true);
},
child: Text("Change colour"),
),
StreamBuilder(
builder: (context, snapshot) {
var bool = snapshot?.data ?? false;
return Text(
"First text",
style:
TextStyle(color: bool ? Colors.red : Colors.green),
);
},
stream: bloc?.colour,
),
],
);
}
@override
void dispose() {
super.dispose();
}
}
I don't understand how to call dispose method of the bloc when using InheritedWidget
. Of course I can create a global variable of bloc and avoid using InheritedWidget
to dispose the bloc using the dispose method which is present in the bloc but I really want to use InheritedWidget
.
Does using the PublishSubject
from rxdart
disposes the streamcontroller
automatically, is it life cycle aware, I couldn't find anything related to this in the documentation. Is there any debugging process to make sure the streamcontroller
is disposed off correctly?
That is not possible using Inheritedwidget
. The widget is not made to handle data, but to share it.
You have to wrap your Inheritedwidget
into a StatefulWidget
and use the dispose of the latter