基于Flutter实现按标题过滤宪法的REST API搜索功能
完善Flutter首页宪法搜索功能实现
要实现输入关键词时调用API过滤宪法数据,只需对现有代码做以下3处修改:
1. 改造SearchBar组件,支持搜索回调
修改SearchBar类,添加搜索输入变化的回调参数,让父组件能接收搜索关键词:
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class SearchBar extends StatelessWidget { // 添加搜索回调参数 final ValueChanged<String> onChanged; // 构造函数接收回调 const SearchBar({super.key, required this.onChanged}); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(vertical: 30), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), child: CupertinoSearchTextField( // 将输入变化传递给父组件 onChanged: onChanged, autofocus: true, itemColor: Colors.black, itemSize: 20, backgroundColor: const Color.fromARGB(255, 185, 204, 218), placeholderStyle: const TextStyle( color: Colors.black, fontSize: 18, ), ), ); } }
2. 在首页绑定搜索回调到控制器方法
修改HomePage中的SearchBar使用方式,将搜索关键词传递给ConstitutionController的getConstitutions方法:
// 替换原来的const SearchBar() SearchBar( onChanged: (value) { // 调用控制器的搜索方法,传入关键词 constitutionController.getConstitutions(value); }, ),
3. 确保控制器API调用逻辑正确
检查ConstitutionController中的getConstitutions方法,确认HttpService.getConstitutions(search)已正确将搜索关键词作为参数传递给后端API(比如作为URL查询参数)。当前代码逻辑已满足需求,无需额外修改:
void getConstitutions(String search) async { try { isLoading(true); // 传递搜索关键词给API服务 dynamic response = await HttpService.getConstitutions(search); if (response.statusCode == 200) { List<dynamic> body = jsonDecode(response.body); List<Constitution> constitutions = body .map((dynamic item) => Constitution.fromJson(item)) .toList(); constitutionList(constitutions); } } catch (err) { // 可添加错误提示逻辑 } finally { isLoading(false); } }
完成以上修改后,用户在搜索栏输入关键词时,会实时调用后端API获取过滤后的宪法数据,并更新首页的卡片列表展示。
内容的提问来源于stack exchange,提问作者lester
相关产品推荐
相关产品推荐

