BIS Tech
BIS Tech

Reputation: 19444

How to catch speed typing on textField widget?

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)),
 )

Upvotes: 2

Views: 1248

Answers (1)

Adelina
Adelina

Reputation: 11891

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));
}

Upvotes: 4

Related Questions