Mahdi Zakizadeh
Mahdi Zakizadeh

Reputation: 645

Rxdart BehaviorSubject make its value null

I have a wired problem with Rxdart BehaviorSubject! I created a screen in flutter that has two TextField and one DropdownButton and I receiving their data with bloc pattern.

But when I change TextFields values, The value of BehaviorSubject that connected to DropdownButton get null and when I change DropdownButton value, the value of two BehaviorSubjects that connected to TextFields gets null.

Also it does not affect widget rendering.

Can anyone help me understand what am I doing wrong here. here is my bloc code:

class Bloc {
  final _type = BehaviorSubject<String>();
  final _amount = BehaviorSubject<String>();
  final _title = BehaviorSubject<String>();

  Stream<String> get type => _type.stream;
  Stream<String> get amount => _amount.stream;
  Stream<String> get title => _title.stream;

  Function(String) get changeType => _type.sink.add;
  Function(String) get changeAmount => _amount.sink.add;
  Function(String) get changeTitle => _title.sink.add;

  createTransaction() {
    final validType = _type.value;
    final validAmount = _amount.value;
    final validTitle = _title.value;

    print(validType);
    print(validAmount);
    print(validTitle);
  }

  dispose() {
    _type.close();
    _amount.close();
    _title.close();
  }

}

Upvotes: 1

Views: 1860

Answers (1)

Mahdi Zakizadeh
Mahdi Zakizadeh

Reputation: 645

So after rewriting code I finally found what was the problem. This was so annoying I hope this answer helps someone else.

The problem was I added provider inside routes so the code was like this:

Route routes(RouteSettings settings) {
  switch(settings.name) {
    case '/app':
      return MaterialPageRoute(
        builder: (context) {
          return MainProvider(child: MainScreen());
        }
      );
    ...
  }
}

And so I changed that to this code and bring all providers in main build function:

class App extends StatelessWidget {
  Widget build(context) {
    return UserProvider(
      child: ListsProvider(
        child: TransactionsFormProvider(
          child: MaterialApp(
            onGenerateRoute: routes,
            ...
          ),
        ),
      ),
    );
  }
}

But finally I didn't understand what the heck is the relation between BehaviorSubject and This solution :))

Upvotes: 1

Related Questions