Hibok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

121 line
2.9 KiB

  1. import 'dart:async';
  2. import 'package:chat/generated/i18n.dart';
  3. import 'package:flutter/material.dart';
  4. /// Custom Search input field, showing the search and clear icons.
  5. class SearchInput extends StatefulWidget {
  6. final ValueChanged<String> onSearchInput;
  7. final Key searchInputKey;
  8. SearchInput(
  9. this.onSearchInput, {
  10. Key key,
  11. this.searchInputKey,
  12. }) : super(key: key);
  13. @override
  14. State<StatefulWidget> createState() {
  15. return SearchInputState(onSearchInput);
  16. }
  17. }
  18. class SearchInputState extends State {
  19. final ValueChanged<String> onSearchInput;
  20. TextEditingController editController = TextEditingController();
  21. Timer debouncer;
  22. bool hasSearchEntry = false;
  23. SearchInputState(this.onSearchInput);
  24. @override
  25. void initState() {
  26. super.initState();
  27. editController.addListener(onSearchInputChange);
  28. }
  29. @override
  30. void dispose() {
  31. editController.removeListener(onSearchInputChange);
  32. editController.dispose();
  33. super.dispose();
  34. }
  35. void onSearchInputChange() {
  36. if (editController.text.isEmpty) {
  37. debouncer?.cancel();
  38. onSearchInput(editController.text);
  39. return;
  40. }
  41. if (debouncer?.isActive ?? false) {
  42. debouncer.cancel();
  43. }
  44. debouncer = Timer(Duration(milliseconds: 500), () {
  45. onSearchInput(editController.text);
  46. });
  47. }
  48. @override
  49. Widget build(BuildContext context) {
  50. return Container(
  51. padding: EdgeInsets.symmetric(
  52. horizontal: 8,
  53. ),
  54. child: Row(
  55. children: <Widget>[
  56. Icon(
  57. Icons.search,
  58. color: Colors.black,
  59. ),
  60. SizedBox(
  61. width: 8,
  62. ),
  63. Expanded(
  64. child: TextField(
  65. keyboardAppearance: Brightness.light,
  66. style: TextStyle(textBaseline: TextBaseline.alphabetic),
  67. decoration: InputDecoration(
  68. hintText: I18n.of(context).search_plach,
  69. border: InputBorder.none,
  70. ),
  71. controller: editController,
  72. onChanged: (value) {
  73. setState(() {
  74. hasSearchEntry = value.isNotEmpty;
  75. });
  76. },
  77. ),
  78. ),
  79. SizedBox(
  80. width: 8,
  81. ),
  82. hasSearchEntry
  83. ? GestureDetector(
  84. child: Icon(
  85. Icons.clear,
  86. color: Colors.black,
  87. ),
  88. onTap: () {
  89. editController.clear();
  90. setState(() {
  91. hasSearchEntry = false;
  92. });
  93. },
  94. )
  95. : SizedBox(),
  96. ],
  97. ),
  98. decoration: BoxDecoration(
  99. borderRadius: BorderRadius.circular(16),
  100. color: Colors.grey[100],
  101. ),
  102. );
  103. }
  104. }