-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
search_box.dart
97 lines (86 loc) · 2.92 KB
/
search_box.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:genshindb/generated/l10n.dart';
import 'package:responsive_builder/responsive_builder.dart';
typedef SearchChanged = void Function(String val);
class SearchBox extends StatefulWidget {
final String? value;
final bool showClearButton;
final SearchChanged searchChanged;
const SearchBox({
Key? key,
this.value,
required this.searchChanged,
this.showClearButton = true,
}) : super(key: key);
@override
_SearchBoxState createState() => _SearchBoxState();
}
class _SearchBoxState extends State<SearchBox> {
final _searchFocusNode = FocusNode();
late TextEditingController _searchBoxTextController;
@override
void initState() {
super.initState();
_searchBoxTextController = TextEditingController(text: widget.value);
_searchBoxTextController.addListener(_onSearchTextChanged);
}
@override
void dispose() {
super.dispose();
_searchBoxTextController.removeListener(_onSearchTextChanged);
_searchBoxTextController.dispose();
}
@override
Widget build(BuildContext context) {
final s = S.of(context);
final theme = Theme.of(context);
final isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;
final maxWidth = MediaQuery.of(context).size.width;
final device = getDeviceType(MediaQuery.of(context).size);
final maxSize = device == DeviceScreenType.mobile && isPortrait ? maxWidth : maxWidth * 0.7;
return Container(
constraints: BoxConstraints(maxWidth: maxSize),
child: Card(
elevation: 3,
margin: const EdgeInsets.all(10),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: Row(
children: <Widget>[
Container(
margin: const EdgeInsets.only(left: 10),
child: const Icon(Icons.search),
),
Expanded(
child: TextField(
controller: _searchBoxTextController,
focusNode: _searchFocusNode,
cursorColor: theme.accentColor,
keyboardType: TextInputType.text,
textInputAction: TextInputAction.go,
decoration: InputDecoration(
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(horizontal: 15),
hintText: '${s.search}...',
),
),
),
if (widget.showClearButton)
IconButton(
icon: const Icon(Icons.close),
onPressed: _cleanSearchText,
),
],
),
),
);
}
void _onSearchTextChanged() => widget.searchChanged(_searchBoxTextController.text);
void _cleanSearchText() {
_searchFocusNode.requestFocus();
if (_searchBoxTextController.text.isEmpty) {
return;
}
_searchBoxTextController.text = '';
}
}