Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamBuilder throws Dirty State saying Invalid Arguments

Tags:

flutter

dart

bloc

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)
like image 312
Pritish Avatar asked Jan 17 '19 04:01

Pritish


1 Answers

The error is because you are trying to sum String + null in this line:

print("pritish" + snapshot.data);

So, to fix your issue use String interpolation:

print("pritish : ${snapshot.data}");

Don't forget to wrap your HomePage widget inside the provider.

 MaterialApp(
        home: Provider(
          child: HomePage()
        ),
      ),
like image 78
diegoveloper Avatar answered Oct 17 '22 07:10

diegoveloper