Raihan
Raihan

Reputation: 37

Flutter : put api response into flutter dropdown menu

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();
              },
            ),

display the data

Upvotes: 1

Views: 985

Answers (1)

harizh
harizh

Reputation: 386

you can use DropdownButtonFormField Widget to show your api response in dropdown menu.

below is my example code...

Explanation for below code :

field declaration :

CategoryModel? _myCategory;
List<CategoryModel> _categories = List<CategoryModel>.empty();

CategoryModel is the Object _myCategory is the object which was selected from that dropdown _categories is the list of object get from api response

finally in the onChanged property you can perform your functionality

Container(
              height: 65.0,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(30.0),
                border: Border.all(
                    color: const Color.fromRGBO(244, 248, 248, 1), width: 2),
              ),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: DropdownButtonHideUnderline(
                      child: ButtonTheme(
                        alignedDropdown: true,
                        child: DropdownButtonFormField<CategoryModel>(
                          dropdownColor: Colors.white,
                          decoration: const InputDecoration(
                              enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.white),
                          )),
                          value: _myCategory,
                          iconSize: 40,
                          isExpanded: true,
                          icon: const Icon(
                            Icons.arrow_circle_right ,
                            color: Color.fromRGBO(39,81,91,1),
                            // size: 35.0,
                          ),
                          // elevation: 8,
                          hint: Text('Select Category'),
                          onChanged: (CategoryModel? newValue) {
                          },
                          items: items = _categories.map((item) {
                            return DropdownMenuItem<CategoryModel>(
                              child: Text(
                                item.name.toString(),
                                style: const TextStyle(
                                  color: Color.fromRGBO(36, 36, 36, 1),
                                  fontStyle: FontStyle.normal,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                              value: item,
                            );
                          }).toList(),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),

enter image description here

enter image description here

Upvotes: 3

Related Questions