Search code examples
dartflutterrxdart

How to update flutter widget using RxDart BehaviorSubject?


Im new to flutter and dart so i have created simple counter flutter app , explained in article.

But when stream does not update widget when subject adds values. can someone help me to find the issue.

my main widget class

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

and Counter widget

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,
                ),
              ],
            ),
          ),
    );
  }
}

and here is my bloc class

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

Can some one help me to find the issue.

Thanks.


Solution

  • You are using two separate instances of CounterBloc in MyHomePage and Counter classes. A simple solution would be to pass the CounterBloc of MyHomePage to Counter:

    MyHomePage

    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    

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

    Counter

    class Counter extends StatefulWidget {
      Counter({Key key, this.bloc}) : super(key: key);
    
      final CounterBloc bloc;
      @override
      _CounterState createState() => _CounterState();
    }
    

    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,
                ),
              ],
            ),
          ),
        );
      }
    }
    

    But in the long run, rather than passing your Bloc explicitly as a parameter, you should use a BlocProvider, which will implicitly assigns the instance of the parent classes' Bloc to your children.