// 独立的搜索框组件 import 'package:flutter/material.dart'; class SearchBarCustom extends StatefulWidget { final ValueChanged? onSearch; final ValueChanged? onChanged; final VoidCallback? onClear; final String hintText; const SearchBarCustom({ super.key, this.onSearch, this.onChanged, this.onClear, this.hintText = '搜索...', }); @override State createState() => _SearchBarCustomState(); } class _SearchBarCustomState extends State { final TextEditingController _controller = TextEditingController(); final FocusNode _focusNode = FocusNode(); @override void dispose() { _controller.dispose(); _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( color: Colors.grey[100], borderRadius: BorderRadius.circular(15), ), child: TextField( controller: _controller, focusNode: _focusNode, decoration: InputDecoration( hintText: widget.hintText, border: InputBorder.none, prefixIcon: const Icon(Icons.search), suffixIcon: _controller.text.isNotEmpty ? IconButton( icon: const Icon(Icons.clear), onPressed: () { _controller.clear(); widget.onClear?.call(); }, ) : null, contentPadding: const EdgeInsets.symmetric( vertical: 15, horizontal: 20, ), ), onChanged: (value) { setState(() {}); // 更新清除按钮显示 widget.onChanged?.call(value); }, onSubmitted: (value) { widget.onSearch?.call(value); _focusNode.unfocus(); }, ), ); } }