LearnToday
LearnToday

Reputation: 2902

How to get textfield value from widget to bloc

I have this setup. I have a widget that holds my search textfield. Now what I want to go is listen and get the text field value in my bloc class and be able to use with different constructors.

Here is the textfield:

TextField(
     controller: _searchinput,
     onChanged: chatBloc.onChatTextChanged.add
);

And here is the bloc class I want to get the value in..

  class ChatBloc extends ChatService {
      ChatBloc.empty();
      ChatBloc(chatroomid) {
        _subject.addStream(fetchFirstListStream(chatroomid));
      }
      ChatBloc.forSearchScroll(chatroomid, [items]) {
        _controller.listen(
            (notification) => loadmoreSearchChats(chatroomid, notification));
       });
     
      loadmoreSearchChats(chatroomid, notification){
         // So I can use the search term here.
      }
    }

I want to have the searchterm value in the ChatBloc.forSearchScroll. constructor and if possible the value should be available as a global value in the bloc class that I can use in other methods of the class. For instance I should be able to do more search filters in the loadmoreSearchChats method with the textfield value.

I tried RxDart BehaviorSubject

BehaviorSubject<String> searchtext;
 Sink<String> get searchtextsetter => searchtext.sink;

And in the widget tried to add the value with:

chatBloc.searchtextsetter.sink.add(value)

It didn't work. Clearly am not doing it the right way. So what would be the right way to do this?

Upvotes: 0

Views: 638

Answers (2)

Shubham Gupta
Shubham Gupta

Reputation: 1997

You can use it like this,

final searchtext = BehaviorSubject<String>();
Function(String) get searchtextsetter => searchtext.sink.add;

TextField(
 controller: _searchinput,
 onChanged: chatBloc.searchtextsetter,
);

Upvotes: 1

Ahmed Jamal
Ahmed Jamal

Reputation: 201

You have to replace

BehaviorSubject<String> searchtext;
Sink<String> get searchtextsetter => searchtext.sink;

with

BehaviorSubject<String> searchtext;
Sink<String> get searchtextsetter => searchtext.sink.add;

and

onChanged: chatBloc.onChatTextChanged.add

with

onChanged: chatBloc.searchtextsetter

Upvotes: 2

Related Questions