Created
September 5, 2021 13:45
-
-
Save VB10/5844ae066ae6144be64d50fa15776188 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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