Flutter Country_picker选中国家无法回显至搜索栏问题求助
解决Flutter country_picker选中国家无法回显到SearchBar的问题
你的问题核心是没有通过状态控制器同步选中的国家到SearchBar,以下是具体解决步骤和修改后的代码:
关键修改点
- 使用
TextEditingController控制SearchBar的显示文本 - 在
onSelect回调中更新控制器的文本内容 - 组件销毁时释放控制器,避免内存泄漏
修改后的完整代码示例
class YourPage extends StatefulWidget { const YourPage({super.key}); @override State<YourPage> createState() => _YourPageState(); } class _YourPageState extends State<YourPage> { // 定义控制器用于控制SearchBar的文本 final TextEditingController _searchController = TextEditingController(); @override void dispose() { // 销毁时释放控制器 _searchController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Container( padding: const EdgeInsets.only(left: 20, right: 20, top: 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( height: 50, width: 250, child: SearchBar( // 绑定控制器 controller: _searchController, onChanged: print, backgroundColor: const MaterialStatePropertyAll(Color(0xffE1E8F6)), leading: const Icon( Icons.location_on, color: Color(0xffFF5A5A), size: 30, ), side: const MaterialStatePropertyAll( BorderSide(color: Color(0xffC5C3C6))), hintText: 'Worldwide', textStyle: MaterialStatePropertyAll( Theme.of(context).textTheme.bodySmall), onTap: () => showCountryPicker( context: context, showPhoneCode: false, countryListTheme: CountryListThemeData( inputDecoration: InputDecoration( prefixIcon: const Icon(Icons.search_rounded), hintText: 'Search a country', hintStyle: Theme.of(context).textTheme.bodySmall, border: OutlineInputBorder( borderRadius: BorderRadius.circular(20), borderSide: const BorderSide(color: Color(0xffC5C3C6)), )), searchTextStyle: Theme.of(context).textTheme.bodySmall, backgroundColor: Colors.white, bottomSheetHeight: 400), onSelect: (Country country) { // 更新控制器文本,实现回显 setState(() { _searchController.text = country.displayName; }); }, ), ), ), // 保留你原Row中的其他组件 ], ), ), // 页面其他内容 ], ), ); } }
补充说明
- 将
YourPage替换为你实际的页面组件名称 - 可根据需求把
country.displayName换成country.name或其他国家字段 - 加入
setState确保UI及时更新(更新controller.text通常会自动触发UI更新,加上更稳妥)
内容的提问来源于stack exchange,提问作者WidgetBear
相关产品推荐
相关产品推荐

