13.1 搜索栏防抖处理
实现步骤:
第 1 步:搜索栏
控制器
lib/pages/search/search_index/controller.dart
1 2
| final TextEditingController searchEditController = TextEditingController();
|
1 2 3 4 5 6
| @override void onClose() { super.onClose(); searchEditController.dispose(); }
|
视图
lib/pages/search/search_index/view.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| AppBar _buildAppBar() { return AppBar( titleSpacing: AppSpace.listItem, title: InputWidget.textBorder( controller: controller.searchEditController, hintText: "You can try T-Shirt", onChanged: (val) { printInfo(info: val); }, ).paddingRight(AppSpace.page), ); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @override Widget build(BuildContext context) { return GetBuilder<SearchIndexController>( init: SearchIndexController(), id: "search_index", builder: (_) { return Scaffold( appBar: _buildAppBar(), body: SafeArea( child: _buildView(), ), ); }, ); }
|
第 2 步:防抖处理
搜索栏防抖是指,当你频繁输入内容的时候,间隔一定的时间拉取数据,而不是频繁的暴力拉取数据。
控制器
lib/pages/search/search_index/controller.dart
1 2
| final searchKeyWord = "".obs;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| void searchDebounce() { debounce( searchKeyWord,
(value) async { if (kDebugMode) { print("debounce -> " + value.toString()); }
update(["search_index"]); },
time: const Duration(milliseconds: 500), );
searchEditController.addListener(() { searchKeyWord.value = searchEditController.text; }); }
|
1 2 3 4 5 6
| @override void onReady() { super.onReady(); searchDebounce(); }
|
第 3 步:首页搜索栏点击
lib/pages/goods/home/controller.dart
1 2 3 4
| void onAppBarTap() { Get.toNamed(RouteNames.searchSearchIndex); }
|
提交代码到 git