| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- // 独立的搜索框组件
- import 'package:flutter/material.dart';
-
- class SearchBarCustom extends StatefulWidget {
- final ValueChanged<String>? onSearch;
- final ValueChanged<String>? onChanged;
- final VoidCallback? onClear;
- final String hintText;
-
- const SearchBarCustom({
- super.key,
- this.onSearch,
- this.onChanged,
- this.onClear,
- this.hintText = '搜索...',
- });
-
- @override
- State<SearchBarCustom> createState() => _SearchBarCustomState();
- }
-
- class _SearchBarCustomState extends State<SearchBarCustom> {
- 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();
- },
- ),
- );
- }
- }
|