我是新手,找不到我想要的解决方案。
我有一个文本字段,我想在几秒钟后在列表中搜索产品代码,并在列表视图中显示与该代码匹配的产品。
有人可以帮我吗?
答案 0 :(得分:0)
尝试一下。
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final TextEditingController controller = TextEditingController();
final Debouncer onSearchDebouncer =
new Debouncer(delay: new Duration(milliseconds: 500));
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: TextField(
controller: this.controller,
onChanged: (val) => this.onSearchDebouncer.debounce(
() => print("text : " + val),
)),
),
),
),
);
}
}
带有计时器的自定义Debouncer
类。
import 'dart:async';
import 'dart:ui';
class Debouncer {
Duration delay;
Timer _timer;
VoidCallback _callback;
Debouncer({this.delay = const Duration(milliseconds: 500)});
void debounce(VoidCallback callback) {
this._callback = callback;
this.cancel();
_timer = new Timer(delay, this.flush);
}
void cancel() {
if (_timer != null) {
_timer.cancel();
}
}
void flush() {
this._callback();
this.cancel();
}
}