Cyrus the Great
Cyrus the Great

Reputation: 5932

flutter: BehaviorSubject not rebuild widget

I am trying to use Rxdart on my statless widget:

class SimplePrioritySelectWidget extends StatelessWidget {
  BehaviorSubject<List<String>> _valueNotifier =
      BehaviorSubject<List<String>>.seeded([]);

I wrap my widget by StreamBuilder:

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: _valueNotifier.stream,
      initialData: options,
      builder: (context, snapshot) {
        print("rebuild");
        return Padding(
          padding: const EdgeInsets.only(top: 25),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 16.h,
              ),

I have a custom drop down widget, I don't know why, when I add a string inside _valueNotifier the builder method not called? and my widget not rebuilded? What is wrong?

  CustomDropdown(
    dropdownMenuItemList: options,
    enableBorderColor: Color(PRIMARY_COLOR_2),
    onChanged: (value) {

      _valueNotifier.value.add(value);
    
    },

  ),

Upvotes: 0

Views: 1113

Answers (2)

Sami Kanafani
Sami Kanafani

Reputation: 15741

I totally agree that the you need to use sink in _valueNotifier

  CustomDropdown(
    dropdownMenuItemList: options,
    enableBorderColor: Color(PRIMARY_COLOR_2),
    onChanged: (value) {
      _valueNotifier.sink.add([value]);
    },

  ),

Upvotes: 1

Nitrodon
Nitrodon

Reputation: 3435

Mutating the value won't notify BehaviorSubject of anything. In order to make BehaviorSubject notify its listeners, you need to provide a different state object.

  CustomDropdown(
    dropdownMenuItemList: options,
    enableBorderColor: Color(PRIMARY_COLOR_2),
    onChanged: (value) {
Sta
      _valueNotifier.value = [..._valueNotifier.value, value];
      // or _valueNotifier.add([..._valueNotifier.value, value]);
    },

  ),

Also, a BehaviorSubject is state and should not be created in a StatelessWidget. If you try anyway, the subject will be created (with the same initial value) every time your widget is rebuilt.

Upvotes: 0

Related Questions