3

I need to display the rows data in the dropdown. Any help is appreciated.

class _MyAppState extends State<MyAppdrop> {
  List<LeadService> payloadListdropdown;
  bool loading = false;
  String _mySelection;

  List<LeadService> payloadFromJson(String str) =>
      List<LeadService>.from(
          json.decode(str).map((x) => LeadService.fromJson(x)));
  String payloadToJson(List<LeadService> data) =>
      json.encode(List<dynamic>.from(data.map((x) => x.toJson())));


  Future<List<LeadService>> requestMethodspinner() async {
    var url = "";
    Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };
    final response = await http.post(url, headers: headers);
    final responseJson = json.decode(response.body);
    print(responseJson);
    print(response.statusCode);
    setState(() {
      loading = true;
      payloadListdropdown = payloadFromJson(response.body);
      loading = false;
    });
    if (response.statusCode == 200) {}
    else {
      throw Exception('Failed to load internet');
    }
    return payloadListdropdown;
  }


  @override
  void initState() {
    super.initState();
    this.requestMethodspinner();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text("DropDown"),
      ),
      body: new Center(
        child: new DropdownButton(
          items: payloadListdropdown.map((item) {
            return new DropdownMenuItem(
              child: new Text("${payloadListdropdown[0].rows[1].sName}"),
              value: item[1].toString(),
            );
          }).toList(),
          onChanged: (newVal) {
            setState(() {
              _mySelection = newVal;
            });
          },
          value: _mySelection,
        ),
      ),
    );
  }
}
class LeadService {
  int status;
  String msg;
  List<Rows> rows;
  String sql;
  dynamic reserved;
  LeadService({
    this.status,
    this.msg,
    this.rows,
    this.sql,
    this.reserved,
  });
  factory LeadService.fromJson(Map<String, dynamic> json) => LeadService(
    status: json["status"],
    msg: json["msg"],
    rows: List<Rows>.from(json["rows"].map((x) => Rows.fromJson(x))),
    sql: json["sql"],
    reserved: json["reserved"],
  );
  Map<String, dynamic> toJson() => {
    "status": status,
    "msg": msg,
    "rows": List<dynamic>.from(rows.map((x) => x.toJson())),
    "sql": sql,
    "reserved": reserved,
  };
}
class Rows {

  String ServicesId;
  String sName;
  String sCode;

  Rows({
    this.ServicesId,
    this.sName,
    this.sCode,

  });
  factory Rows.fromJson(Map<String, dynamic> json) => Rows(
    //dropdownservicelist
    ServicesId:json["ServicesId"],
    sName:json["sName"],
    sCode:json["sCode"],

  );

  Map<String, dynamic> toJson() => {
    //dropdownservicelist
    "ServicesId" :ServicesId,
    "sName" : sName,
    "sCode" : sCode,

  };
}


Json data:

[
  {
    "status": 200,
    "msg": "Ok",
    "refcode": -1,
    "trows": 13,
    "rows": [
      {
        "ServicesId": "3",
        "sName": "CFS",
        "sCode": "CF"
      },
      {
        "ServicesId": "2",
        "sName": "Container aGENT",
        "sCode": "CA"
      },
      {
        "ServicesId": "1",
        "sName": "Custom",
        "sCode": "CB"
      }
    ],
    "sql": "Services",
    "reserved": null
  }
]

1 Answer 1

2
    class _MyAppState extends State<MyAppdrop> {
      Map payloadListdropdown;
      Map _mySelection;
      bool _loading = true;

      requestMethodspinner() async {
        var url = "";
        Map<String, String> headers = {
          'Content-type': 'application/json',
          'Accept': 'application/json',
        };
        final response = await http.post(url, headers: headers);
        final responseJson = json.decode(response.body);
        print(responseJson);
        print(response.statusCode);

        if (response.statusCode == 200) {
          setState(() {
          loading = false;
          payloadListdropdown = json.decode(response.body)[0];
          _mySelection = payloadListdropdown['rows'][0];
        });
       }
        else {
          setState((){
          loading = false;
          });
          throw Exception('Failed to load internet');
        }
      }


      @override
      void initState() {
        super.initState();
        requestMethodspinner();
      }

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: AppBar(
            title: Text("DropDown"),
          ),
          body: new Center(
            child: _loading && payloadListdropdown == null ?
              ListTile(
                 title: Text('Loading...'),
                 leading:CircularProgressIndicator(),
              )
              :
              payloadListdropdown == null ?
              ListTile(
                 title: Text('Internet not available or Nothing found !'),
              )
              : DropdownButton(
              items: payloadListdropdown['rows'].map<DropDownMenuItem<Map>>((item) {
                return new DropdownMenuItem(
                  child: new Text(item['sName']),
//Other fields like sCode etc..
                  value: item,
                );
              }).toList(),
              onChanged: (newVal) {
                setState(() {
                  _mySelection = newVal;
                  print(_mySelection.toString())
                });
              },
              value: _mySelection,
            ),
          ),
        );
      }
    }
Sign up to request clarification or add additional context in comments.

11 Comments

I am not getting this. can you help me with my above code.it will be very help full.
No its not working out . i am getting this error . Error: The argument type 'DropdownMenuItem<Map<dynamic, dynamic>> Function(Map<dynamic, dynamic>)' can't be assigned to the parameter type 'DropdownMenuItem<Map<dynamic, dynamic>> Function(LeadService)'.
child: new DropdownButton( items: payloadListdropdown.map((item) { print({payloadListdropdown[0].rows[1].sName}); return new DropdownMenuItem( child: new Text("${payloadListdropdown[0].rows[0].sName}"), ); }).toList(), onChanged: (newVal) { setState(() { _mySelection = newVal; }); }, value: _mySelection, ),
by using this above code i am only getting only 1st value in the DropDown. @SCANDINAVIA
Do not use LeadService Class/Object ! You can directly get the json and assign it to Map through the method Map.from(json_file) then replace all LeadService instances to Map instance
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.