Home > Mobile >  dropdown search flutter type 'List<dynamic>' is not a subtype of type 'Map<S
dropdown search flutter type 'List<dynamic>' is not a subtype of type 'Map<S

Time:01-27

i am trying to make a dropdown button with firebase api

DropdownSearch<Tipe>(
    popupProps: PopupProps.dialog(
    showSearchBox: true,
    itemBuilder: (context, item, isSelected) => ListTile(
         title: Text(item.name),
      ),
    ),
    dropdownDecoratorProps: DropDownDecoratorProps(
         dropdownSearchDecoration: InputDecoration(
              labelText: "Tipe",
         ),
    ),
    onChanged: (value) {
        setState(() {
             idTipe = value?.id;
             namaTipe = value?.name;
        });
    },
    dropdownBuilder: (context, selectedItem) =>
        Text(selectedItem?.name ?? 'not selected'),
        asyncItems: (text) async {
             var response = await http.get(Uri.parse("$api/tipe.json"));
             if (response.statusCode != 200) {
                 return [];
             }
             List tipe = (json.decode(response.body)
                  as Map<String, dynamic>)['value'];
             List<Tipe> modeltipe = [];
             tipe.forEach((element) {
                   modeltipe.add(Tipe(id: element['id'], name: element['name']));
             });
             return modeltipe;
    },
),

i am trying to follow this code for json file

import 'dart:convert';

Tipe tipeFromJson(String str) => Tipe.fromJson(json.decode(str));

String tipeToJson(Tipe data) => json.encode(data.toJson());

class Tipe {
  Tipe({
    required this.id,
    required this.name,
  });

  String id;
  String name;

  factory Tipe.fromJson(Map<String, dynamic> json) => Tipe(
        id: json["id"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
      };
  @override
  String toString() => name;
}

and when I try to run the program, and the results of the process of retrieving data from the firebase realtime database appear like this

type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

dropdown result

Does anyone know a solution to this problem?

CodePudding user response:

Change

List tipe = (json.decode(response.body) as Map<String, dynamic>)['value'];

to

List tipe = (json.decode(response.body)['value'];

CodePudding user response:

You are trying to pass a map into a list but you don't treat it right. You have to cast the map to a list like for example: return jsonResponse.map((e) => YourClass.fromJson(e)).toList();

  • Related