Created
February 15, 2024 21:45
-
-
Save austinevick/ae8be44a2ecc848ebb99012ad2dbc0ab to your computer and use it in GitHub Desktop.
Flutter searchAnchor demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SearchAnchorDemo extends StatefulWidget { | |
const SearchAnchorDemo({super.key}); | |
@override | |
State<SearchAnchorDemo> createState() => _SearchAnchorDemoState(); | |
} | |
class _SearchAnchorDemoState extends State<SearchAnchorDemo> { | |
List<String> fruits = [ | |
'Apple', | |
'Grape', | |
'Avocado', | |
'Banana', | |
'Oranges', | |
'Mango', | |
'Blueberry', | |
'Apricot', | |
'Strawberries', | |
'Pineapple', | |
'Papaya', | |
'Pomegranate', | |
'Raspberries' | |
]; | |
final searchController = SearchController(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: SafeArea( | |
minimum: const EdgeInsets.all(25), | |
child: Column( | |
children: [ | |
SearchAnchor( | |
searchController: searchController, | |
builder: (context, controller) => SearchBar( | |
leading: const Text('Search'), | |
trailing: const [Icon(Icons.search)], | |
onTap: () { | |
searchController.openView(); | |
}, | |
), | |
suggestionsBuilder: (context, controller) => | |
List.generate(fruits.length, (i) => fruits[i]) | |
.where((element) => element | |
.toLowerCase() | |
.startsWith(controller.value.text.toLowerCase())) | |
.map((e) => ListTile( | |
title: Text(e), | |
onTap: () { | |
controller.closeView(e); | |
FocusScope.of(context).unfocus(); | |
}, | |
))), | |
Expanded( | |
child: Center( | |
child: searchController.text.isEmpty | |
? const Text('No keyword') | |
: Text('Keyword: ${searchController.value.text}'), | |
), | |
), | |
], | |
)), | |
); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment