1

I'm making a search function that calls events every TextFormField Onchanged and trying to add debouncer to limit its api calls. I'm trying this code from this link. When I type and wait for 1 second its working. But when I continue to add another letter nothing happens. It doesn't even trigger the mapEventToState and transformEvents function when I added a break to it. I'm using flutter_bloc: ^6.1.3

TextFormField:

TextFieldTemplate(
onChanged: (value) 
{
    search = _searchController.text;
     BlocProvider.of<ListBloc>(context).add(
          SearchListEvent(
              search: search,
              limit: PAGE_SIZE,
              offset: pageKey));
},
),

Bloc:

@override
Stream<Transition<ListEvent, ListState>>
  transformEvents(Stream<ListEvent> events, transitionFn) {
final defferedEvents = events
    .where((e) => e is SearchListEvent)
    .debounceTime(const Duration(seconds: 1))
    .distinct()
    .switchMap(transitionFn);
final forwardedEvents = events
    .where((e) => e is! SearchListEvent)
    .asyncExpand(transitionFn);
return forwardedEvents.mergeWith([defferedEvents]);
}


@override
Stream<ListState> mapEventToState(ListEvent event,) async* {
if (event is SearchListEvent) {
  yield ListLoadInProgressState();
  final failureOrSearch = await getProduct(Params(
    search: event.search,
    offset: event.offset,
    limit: event.limit,
  ));
  yield* _eitherLoadedOrErrorState(failureOrSearch);
} 
}
unice
  • 2,655
  • 5
  • 43
  • 78
  • Hi, [Does this answer your question ?](https://stackoverflow.com/questions/63367800/flutter-bloc-does-not-change-textformfield-initialvalue) – anirudh Jul 05 '21 at 05:53
  • I suppose that _searchController not added to your search text field. You can also use `value` from onChanged callback instead: `BlocProvider.of(context).add(SearchListEvent(search: value, limit: PAGE_SIZE, offset: pageKey));` – Mol0ko Jul 05 '21 at 07:16
  • @Mol0ko My only problem was the `transformEvents` to add `debouncer` to not spam API every `Onchanged`. If I remove `transformEvents` function in the bloc, everything thing works. – unice Jul 05 '21 at 07:27
  • @unice is your problem solved? or you still need to debounce SearchListEvent? – Mol0ko Jul 05 '21 at 07:51
  • @Mol0ko Its not yet solved, I need the debouncer in the bloc. But like I said in the question above, it only triggers in the first search. – unice Jul 05 '21 at 08:00
  • @unice Ok. Could you provide code of your SearchListEvent? I suppose that it is not Equatable and distinct() operator filters all events as same – Mol0ko Jul 05 '21 at 08:09
  • I think its already solved. I just commented the .distinct() and it works for now. Don't know if that's the fix but will test it for a while. This will only debounce the `SearchListEvent` and will not debounce other events just like what I wanted. Thanks guys – unice Jul 05 '21 at 08:35

0 Answers0