I have an API displaying data and I want to put it in the dropdown menu of the flutter app. I can display it in the text but when I try to create a dropdown menu I can't make it yet
so I want to make a dropdown menu from API response like this
{
"status": "success",
"message": "Routes Requested !",
"data": [
{
"id": 1,
"kode_trayek": "603",
"titik_awal": "Claudia Krajcik V",
"titik_akhir": "Gust Conn",
"created_at": "1996-11-01T01:18:26.000000Z",
"updated_at": "1980-09-18T04:49:44.000000Z",
"deleted_at": null
},
{
"id": 2,
"kode_trayek": "539",
"titik_awal": "Mrs. Tianna Von",
"titik_akhir": "Anais Dibbert DVM",
"created_at": "1973-07-04T07:14:05.000000Z",
"updated_at": "1993-12-11T22:14:31.000000Z",
"deleted_at": null
}
]
}
and this is an example of my code to fetch data from API
Future<List<Data>> fetchData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String? accessToken = sharedPreferences.getString("token");
final response = await http.get(
Uri.parse("https://exampleapi.id/api/routes"),
headers: {
'Authorization': 'Bearer $accessToken',
},
);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
List<dynamic> jsonResponse = map["data"];
return jsonResponse.map((data) => new Data.fromJson(data)).toList();
} else {
throw Exception('Unexpected error occured!');
}
}
class Data {
final int id;
final String titik_awal;
final String titik_akhir;
Data({
required this.id,
required this.titik_awal,
required this.titik_akhir,
});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
id: json['id'],
titik_awal: json['titik_awal'],
titik_akhir: json['titik_akhir'],
);
}
}
and in class _RouteState extends State there is this code
late Future<List<Data>> futureData;
@override
void initState() {
super.initState();
futureData = fetchData();
}
and here's how I display the data
FutureBuilder<List<Data>>(
future: futureData,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Data>? data = snapshot.data;
return ListView.builder(
physics: NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: data!.length,
itemBuilder: (BuildContext context, int index) {
return Container(
margin: EdgeInsets.only(bottom: 12),
child: Column(children: [
Text(data[index].id.toString()),
Text(data[index].titik_awal),
Text(data[index].titik_akhir),
]),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default show a loading spinner.
return const CircularProgressIndicator();
},
),

