I want to create a google type search bar.
Every time user types in something – app will make a API request to backend and show results in a dropdown below the search bar just like google does.
But I have other content under my search bar which gets pushed down everytime dropdown opens up.
If I use Positioned() widget then the dropdown list only occupied the predefined space provided in parent stack widget.
Code I tried:
import 'package:flutter/material.dart';
class X1 extends StatefulWidget {
const X1({super.key});
@override
State<X1> createState() => _X1State();
}
class _X1State extends State<X1> {
bool visible = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Stack(
children: [
TextButton(
onPressed: () {
setState(() {
visible = !visible;
});
},
child: Text('Button'),
),
Positioned.fromRelativeRect(
rect: RelativeRect.fromLTRB(0, 20, 0, 0),
child: Visibility(
child: Container(width: 50, height: 50, color: Colors.pink),
visible: visible,
),
),
],
),
Container(width: 50, height: 50, color: Colors.green),
],
));
}
}
2
Answers
Try the
Autocomplete
widget. The following code should give you something like thisThe data class
The api call function
The Autocomplete widget. A debouncing method before calling the api here, might be ideal to avoid calling on each keystroke.
For more examples and how the results are customizable, see this answer