这是CaiYouHui前端,一个关于flutter的安卓app,前端使用flutter实现

app_search_bar.dart 1.9KB

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