如何使用RxDart BehaviorSubject更新Flutter小部件?

时间:2019-05-05 19:51:26

标签: dart flutter rxdart

对于Flutter和Dart还是陌生的,所以我创建了一个简单的Counter Flutter应用程序,如文章所述。

但是当主题添加值时流不更新小部件时。 有人可以帮我找到问题吗?

我的主要小部件类

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  CounterBloc _counterBloc = new CounterBloc(initialCount: 0);
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Counter(),
      floatingActionButton: FloatingActionButton(
        onPressed: _counterBloc.increment,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

和“计数器”小部件

class Counter extends StatefulWidget {
  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  CounterBloc _counterBloc = new CounterBloc(initialCount: 1);
  @override
  void dispose() {
    _counterBloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: _counterBloc.counterObservable,
      builder: (context, snapshot) => Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'You have pushed the button this many times:',
                ),
                Text(
                  '${snapshot.hasData}',
                  style: Theme.of(context).textTheme.display1,
                ),
              ],
            ),
          ),
    );
  }
}

这是我的集团课程

class CounterBloc {
  int initialCount =
      1; //if the data is not passed by paramether it initializes with 0
  BehaviorSubject<int> _subjectCounter;

  CounterBloc({this.initialCount}) {
    _subjectCounter = new BehaviorSubject<int>.seeded(
        this.initialCount); //initializes the subject with element already
  }

  Observable<int> get counterObservable => _subjectCounter.stream;

  void increment() {
    initialCount++;
    print(initialCount);
    _subjectCounter.add(initialCount);
  }

  void decrement() {
    initialCount--;
    _subjectCounter.add(initialCount);
  }

  void dispose() {
    _subjectCounter.close();
  }
}

有人可以帮我找到问题吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您正在CounterBlocMyHomePage类中使用Counter的两个单独实例。一种简单的解决方案是将CounterBloc的{​​{1}}传递到MyHomePage

Counter

但是从长远来看,您应该使用 class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { CounterBloc _counterBloc = CounterBloc(initialCount: 0); @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Counter(bloc: _counterBloc,), floatingActionButton: FloatingActionButton( onPressed: _counterBloc.increment, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } class Counter extends StatefulWidget { Counter({Key key,this.bloc}) : super(key: key); final CounterBloc bloc ; @override _CounterState createState() => _CounterState(); } class _CounterState extends State<Counter> { CounterBloc _counterBloc ; @override void dispose() { _counterBloc.dispose(); super.dispose(); } @override Widget build(BuildContext context) { CounterBloc _counterBloc = widget.bloc; return StreamBuilder( stream: _counterBloc.counterObservable, builder: (context, snapshot) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text('${snapshot.data}', style: Theme.of(context).textTheme.display1, ), ], ), ),); } } ,而不是将Bloc作为参数显式传递,这将隐式将父类的BlocProvider实例分配给你的孩子们。