I am trying the bloc pattern for my flutter app. I want to change colour of text field when the stream value changes.
Following is my bloc 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();
}
}
Following is my Inherited Widget
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;
}
}
Following is my main class
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
final bloc = Provider.of(context);
return Column(
children: <Widget>[
RaisedButton(
onPressed: () {
bloc.changeColour(true);
},
child: Text("Change colour"),
),
StreamBuilder(
builder: (context, snapshot) {
print("pritish" + snapshot.data);
return Text(
"First text",
style:
TextStyle(color: snapshot.hasData ? Colors.red : Colors.green),
);
},
stream: bloc?.colour,
),
],
);
}
}
Following is the exception thrown
flutter: The following ArgumentError was thrown building StreamBuilder<bool>(dirty, state:
flutter: _StreamBuilderBaseState<bool, AsyncSnapshot<bool>>#24b36):
flutter: Invalid argument(s)
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 _StringBase.+ (dart:core/runtime/libstring_patch.dart:251:57)
flutter: #1 _HomePageState.build.<anonymous closure> (package:bloc_pattern_for_booleans/main.dart:42:29)