13.2 推荐关键词列表
实现步骤:
第 1 步:数据模型
json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| [ { "id": 42, "name": "beanie", "slug": "beanie", "description": "", "count": 1, "_links": { "self": [ { "href": "https://wp.ducafecat.tech/wp-json/wc/v3/products/tags/42" } ], "collection": [ { "href": "https://wp.ducafecat.tech/wp-json/wc/v3/products/tags" } ] } } ]
|
model
第 2 步:API 接口
请求数据 model
lib/common/models/request/product.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class TagsReq { final int? page; final int? prePage; final String? search; final String? slug;
TagsReq({ this.page, this.prePage, this.search, this.slug, });
Map<String, dynamic> toJson() => { 'page': page ?? 1, 'pre_page': prePage ?? 10, 'search': search ?? "", 'slug': slug ?? "", }; }
|
lib/common/api/product.dart
1 2 3 4 5 6 7 8 9 10 11 12 13
| static Future<List<TagsModel>> tags(TagsReq? req) async { var res = await WPHttpService.to.get( '/products/tags', params: req?.toJson(), );
List<TagsModel> tags = []; for (var item in res.data) { tags.add(TagsModel.fromJson(item)); } return tags; }
|
第 3 步:控制器
lib/pages/search/search_index/controller.dart
1 2
| List<TagsModel> tagsList = [];
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| Future<bool> _loadSearch(String keyword) async { if (keyword.trim().isEmpty == true) { tagsList.clear(); return tagsList.isEmpty; }
var result = await ProductApi.tags(TagsReq( search: keyword, ));
tagsList.clear();
if (result.isNotEmpty) { tagsList.addAll(result); }
return tagsList.isEmpty; }
|
1 2 3 4 5 6 7 8 9 10 11 12
| void searchDebounce() { debounce( ...
await _loadSearch(value as String); update(["search_index"]); }, ... }
|
1 2
| void onListItemTap(TagsModel model) {}
|
第 4 步:视图
lib/pages/search/search_index/view.dart
1 2 3 4 5 6 7 8 9 10 11
| Widget _buildListItem(TagsModel item) { return ListTile( title: TextWidget.body1(item.name ?? ""), trailing: IconWidget.icon( Icons.north_west, color: AppColors.primary, ), onTap: () => controller.onListItemTap(item), ); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| Widget _buildList() { return ListView.separated( itemBuilder: (BuildContext context, int index) { TagsModel item = controller.tagsList[index]; return _buildListItem(item); }, separatorBuilder: (BuildContext context, int index) { return const Divider(); }, itemCount: controller.tagsList.length, ); }
|
1 2 3 4
| Widget _buildView() { return _buildList(); }
|
提交代码到 git