Framework: Flutter
Platform: Web
I have the following code which renders a TextField. A ListView is rendered below the TextField using an Overlay when the TextField has focus. The intent of this widget is to function as a drop down menu. However, the onTap() callback of the ListTile's inside the ListView do nothing when tapped!
import 'package:flutter/material.dart';
class CountriesField extends StatefulWidget {
@override
_CountriesFieldState createState() => _CountriesFieldState();
}
class _CountriesFieldState extends State<CountriesField> {
final FocusNode _focusNode = FocusNode();
OverlayEntry? _overlayEntry;
List<String> countries = ['Lebanon', 'Syria', 'India'];
@override
void initState() {
super.initState();
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
_overlayEntry = _createOverlayEntry();
Overlay.of(context).insert(_overlayEntry!);
} else {
_overlayEntry!.remove();
}
});
}
OverlayEntry _createOverlayEntry() {
RenderBox? renderBox = context.findRenderObject() as RenderBox?;
var size = renderBox?.size;
var offset = renderBox?.localToGlobal(Offset(0, size!.height + 5.0));
return OverlayEntry(
builder: (context) => Positioned(
left: offset?.dx,
top: offset?.dy,
width: size?.width,
child: Material(
elevation: 4.0,
child: SizedBox(
width: 200,
height: 300,
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: countries.length,
itemBuilder: (BuildContext context, index) {
return ListTile(
title: Text(countries[index]),
onTap: () {
print(countries[index]);
},
);
},
),
),
),
),
);
}
@override
void dispose() {
_focusNode.dispose();
_overlayEntry?.remove();
super.dispose();
}
@override
Widget build(BuildContext context) {
return TextFormField(
focusNode: _focusNode,
decoration: InputDecoration(labelText: 'Country'),
);
}
}
P.S.: I am aware of the many drop down and searchable drop down packages available already, however, I need to make quite a specific drop down search widget for a project I'm doing and need to solve this problem.