StreamBuilder 抛出脏状态说无效参数

StreamBuilder throws Dirty State saying Invalid Arguments

我正在为我的 flutter 应用尝试 bloc 模式。我想在流值更改时更改文本字段的颜色。

以下是我的集团代码

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;
  }

}

以下是我的主要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,
        ),
      ],
    );
  }

}

下面是抛出的异常

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)

错误是因为您试图在这一行中对 String + null 求和:

print("pritish" + snapshot.data);

因此,要解决您的问题,请使用字符串插值:

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

不要忘记将您的主页小部件包装在提供程序中。

 MaterialApp(
        home: Provider(
          child: HomePage()
        ),
      ),