2

This way called everytime the input changes. The problem is when user types fast, calling api every time and search result is changing always. (called google map autoComplete api)

How to call api when user stop typing? (Not close keyboard or onSaved)

TextField(
      decoration: _inputStyle(),
      cursorColor: Palette.defaultColor,
      controller: _textEditingController,
     onChanged: (value) => setState(() => _autocompletePlace(value)),
 )
BIS Tech
  • 17,000
  • 12
  • 99
  • 148

1 Answers1

4

I would create Debouncer, it would delay the execution of your code by chosen timer.

E.g. user enters '123' - the execution would be delayed by 200ms, user enters '4', last execution is canceled and another delay is created. If user does not enter new data for 200ms, _autocompletePlace("1234") is gonna be executed

import 'package:flutter/foundation.dart';
import 'dart:async';

class Debouncer {
  final int milliseconds;
  VoidCallback action;
  Timer _timer;

  Debouncer({ this.milliseconds });

  run(VoidCallback action) {
    if (_timer != null) {
      _timer.cancel();
    }

    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }
}
final _debouncer = Debouncer(milliseconds: 200);

onTextChange(String text) {
  _debouncer.run(() => _autocompletePlace(value));
}
Adelina
  • 10,915
  • 1
  • 38
  • 46
  • there is no need in reinventing the wheel: https://pub.dev/packages/stream_transform – pskink Nov 29 '19 at 10:25
  • This is not reinventing the wheel. It's simply using the Timer instead of streams – Adelina Nov 29 '19 at 10:28
  • 1
    and `Stream`s are most likely the best way to follow in such cases - i could bet that for searching OP uses some kind of async method returning `Future` so its the best job for `Stream.asyncMap` method – pskink Nov 29 '19 at 10:30
  • @pskink can you give a exaple using `Stream.asyncMap`? – BIS Tech Nov 29 '19 at 10:33
  • 2
    @BloodLoss there is some examples how to do it with streams over rxDart lib: https://github.com/ReactiveX/rxdart/blob/master/example/flutter/github_search/lib/search_bloc.dart @pskink but I am also curious what do you mean by `Stream.asyncMap` :o – Adelina Nov 29 '19 at 10:38