Skip to content

Instantly share code, notes, and snippets.

@VB10
Created September 5, 2021 13:45
Show Gist options
  • Save VB10/5844ae066ae6144be64d50fa15776188 to your computer and use it in GitHub Desktop.
Save VB10/5844ae066ae6144be64d50fa15776188 to your computer and use it in GitHub Desktop.
class SearchField extends StatefulWidget {
final void Function(String value) onChanged;
const SearchField({Key? key, required this.onChanged}) : super(key: key);
@override
_SearchFieldState createState() => _SearchFieldState();
}
class _SearchFieldState extends State<SearchField> {
late CancelableOperation<void> cancellableOperation;
final _delayTime = Duration(milliseconds: 300);
@override
void initState() {
super.initState();
_start();
}
void _start() {
cancellableOperation = CancelableOperation.fromFuture(
Future.delayed(_delayTime),
onCancel: () {
print('Canceled');
},
);
}
void _onItemChanged(String value) {
cancellableOperation.cancel();
_start();
cancellableOperation.value.whenComplete(() {
widget.onChanged(value);
});
}
@override
Widget build(BuildContext context) {
return TextField(
onChanged: _onItemChanged,
decoration: InputDecoration(prefixIcon: Icon(Icons.search)),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment