|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+// 独立的搜索框组件
|
|
|
2
|
+import 'package:flutter/material.dart';
|
|
|
3
|
+
|
|
|
4
|
+class SearchBarCustom extends StatefulWidget {
|
|
|
5
|
+ final ValueChanged<String>? onSearch;
|
|
|
6
|
+ final ValueChanged<String>? onChanged;
|
|
|
7
|
+ final VoidCallback? onClear;
|
|
|
8
|
+ final String hintText;
|
|
|
9
|
+
|
|
|
10
|
+ const SearchBarCustom({
|
|
|
11
|
+ super.key,
|
|
|
12
|
+ this.onSearch,
|
|
|
13
|
+ this.onChanged,
|
|
|
14
|
+ this.onClear,
|
|
|
15
|
+ this.hintText = '搜索...',
|
|
|
16
|
+ });
|
|
|
17
|
+
|
|
|
18
|
+ @override
|
|
|
19
|
+ State<SearchBarCustom> createState() => _SearchBarCustomState();
|
|
|
20
|
+}
|
|
|
21
|
+
|
|
|
22
|
+class _SearchBarCustomState extends State<SearchBarCustom> {
|
|
|
23
|
+ final TextEditingController _controller = TextEditingController();
|
|
|
24
|
+ final FocusNode _focusNode = FocusNode();
|
|
|
25
|
+
|
|
|
26
|
+ @override
|
|
|
27
|
+ void dispose() {
|
|
|
28
|
+ _controller.dispose();
|
|
|
29
|
+ _focusNode.dispose();
|
|
|
30
|
+ super.dispose();
|
|
|
31
|
+ }
|
|
|
32
|
+
|
|
|
33
|
+ @override
|
|
|
34
|
+ Widget build(BuildContext context) {
|
|
|
35
|
+ return Container(
|
|
|
36
|
+ decoration: BoxDecoration(
|
|
|
37
|
+ color: Colors.grey[100],
|
|
|
38
|
+ borderRadius: BorderRadius.circular(15),
|
|
|
39
|
+ ),
|
|
|
40
|
+ child: TextField(
|
|
|
41
|
+ controller: _controller,
|
|
|
42
|
+ focusNode: _focusNode,
|
|
|
43
|
+ decoration: InputDecoration(
|
|
|
44
|
+ hintText: widget.hintText,
|
|
|
45
|
+ border: InputBorder.none,
|
|
|
46
|
+ prefixIcon: const Icon(Icons.search),
|
|
|
47
|
+ suffixIcon: _controller.text.isNotEmpty
|
|
|
48
|
+ ? IconButton(
|
|
|
49
|
+ icon: const Icon(Icons.clear),
|
|
|
50
|
+ onPressed: () {
|
|
|
51
|
+ _controller.clear();
|
|
|
52
|
+ widget.onClear?.call();
|
|
|
53
|
+ },
|
|
|
54
|
+ )
|
|
|
55
|
+ : null,
|
|
|
56
|
+ contentPadding: const EdgeInsets.symmetric(
|
|
|
57
|
+ vertical: 15,
|
|
|
58
|
+ horizontal: 20,
|
|
|
59
|
+ ),
|
|
|
60
|
+ ),
|
|
|
61
|
+ onChanged: (value) {
|
|
|
62
|
+ setState(() {}); // 更新清除按钮显示
|
|
|
63
|
+ widget.onChanged?.call(value);
|
|
|
64
|
+ },
|
|
|
65
|
+ onSubmitted: (value) {
|
|
|
66
|
+ widget.onSearch?.call(value);
|
|
|
67
|
+ _focusNode.unfocus();
|
|
|
68
|
+ },
|
|
|
69
|
+ ),
|
|
|
70
|
+ );
|
|
|
71
|
+ }
|
|
|
72
|
+}
|