Reputation: 101
I'm implementing a basic SearchBar widget in my first mobile Flutter app, based on the code sample provided in the Flutter Docs for SearchBar.
The issue I'm facing is that the SearchBar remains focused when the leading "back-arrow" icon button is pressed when trying to exit the (default) search view, which contains suggestions. Due to this, the keyboard remains open on mobile devices.
Moreover, when the search view is open, pressing the device's back button first closes the keyboard, then pressing back again closes the search view and puts focus back on the SearchBar, which opens the keyboard again. This is terrible UX and coupled with the fact that I'm new to Flutter, I am sure that I am doing something incorrectly.
I've tried different approaches:
Here's my code (without the _focusNode part added in):
class _AddressSearchBarState extends State<AddressSearchBar> {
@override
Widget build(BuildContext context) {
SearchController? searchController;
return Container(
padding: const EdgeInsets.all(20.0),
child: SearchAnchor(
isFullScreen: false,
viewLeading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
if (searchController != null) {
searchController?.closeView(null);
}
},
color: Colors.black,
),
builder: (BuildContext context, SearchController controller) {
searchController = controller;
return SearchBar(
autoFocus: false,
hintText: "Looking for an Address?",
padding: const MaterialStatePropertyAll<EdgeInsets>(
EdgeInsets.symmetric(horizontal: 16.0)
),
onTap: () {
controller.openView(); // cannot use searchController due to null possibility
},
onChanged: (_) {
controller.openView();
},
leading: const Icon(Icons.search),
);
},
suggestionsBuilder: (context, controller) => {}, // TODO: populate with Google Maps suggestions
),
);
}
}
Upvotes: 3
Views: 396
Reputation: 445
A better solution is to wrap the SearchBar
widget in your code with ExcludeFocus
.
References:
Upvotes: 1
Reputation: 4083
This worked for me:
viewLeading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
WidgetsBinding.instance.addPostFrameCallback((_) {
FocusScope.of(context).unfocus();
});
Navigator.pop(context);
},
),
Upvotes: 2