-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearchbar.dart
107 lines (100 loc) · 2.64 KB
/
searchbar.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
98
99
100
101
102
103
104
105
106
107
import 'package:flutter/material.dart';
class SearchBarWidget extends StatelessWidget {
const SearchBarWidget({super.key});
final List<String> fruits = const ['apple', 'oranges', 'melon'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SeachBar Widget'),
actions: [
IconButton(
onPressed: () {
showSearch(
context: context,
delegate: CustomSearchDelegateString(fruits));
},
icon: const Icon(Icons.search),
)
],
),
);
}
}
class CustomSearchDelegateString extends SearchDelegate {
CustomSearchDelegateString(this.fruits);
List<String> fruits;
// clear the search tex
@override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = '';
},
icon: const Icon(Icons.clear),
),
];
}
// second overwrite to pop out of search menu
@override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, null);
},
icon: const Icon(Icons.arrow_back),
);
}
// third overwrite to show query result
@override
Widget buildResults(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in fruits) {
if (fruit.contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
padding: const EdgeInsets.only(left: 10),
shrinkWrap: true,
itemBuilder: (context, index) {
String fruit = matchQuery[index];
return ListTile(
dense: true,
contentPadding: const EdgeInsets.all(0),
title: Text(
fruit,
style: const TextStyle(fontSize: 15),
));
},
);
}
// last overwrite to show the
// querying process at the runtime
@override
Widget buildSuggestions(BuildContext context) {
List<String> matchQuery = [];
for (var fruit in fruits) {
if (fruit.contains(query.toLowerCase())) {
matchQuery.add(fruit);
}
}
return ListView.builder(
itemCount: matchQuery.length,
padding: const EdgeInsets.only(left: 10),
shrinkWrap: true,
itemBuilder: (context, index) {
String fruit = matchQuery[index];
return ListTile(
dense: true,
contentPadding: const EdgeInsets.all(0),
title: Text(
fruit,
style: const TextStyle(fontSize: 15),
));
},
);
}
}