Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter DropdownButtonFormField is not working

I'm trying to populate the drop down by fetching the values from API. When I click the drop down,the values are being shown,when I try to select a value,following error is thrown

 items.isEmpty || value == null || items.where((DropdownMenuItem<T> item) => item.value == value).length == 1': is not true.

values in the list are not empty

When I tried to remove 'value' property of drop down, the error is not shown but the drop down is not showing the selected value

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:something/Utils/formServices.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';
import 'package:intl/intl.dart';
import 'dart:convert';

String insurer;
String package;
List insCat = List();
List insurers = List();
List<DropdownMenuItem> items = [];

class AddOrEditPack extends StatefulWidget{
  @override
  AddOrEditPackState createState() =>AddOrEditPackState();
}

class AddOrEditPackState extends State<AddOrEditPack>{
  final formKey = GlobalKey<FormState>();
  String insuranceCategory = ' ';

  @override
  void initState() {
    getCategories();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text('Contact Us'),
          ),
          drawer: Drawer(
            child: ListView(
              children: <Widget>[
                ListTile(
                  title: Text("Home"),
                ),
              ],
            ),
          ),
          body:
          Form(
            key:formKey,
            child: ListView(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  child: DropdownButtonFormField<String>(
                    hint:Text('Insurance Category'),
                    items: insCat.map((item) {
                      return new DropdownMenuItem<String>(
                        child: new Text(item['name']),
                        // value: item['name'],
                      );
                    }).toList(),
                    onChanged: (String newValue) {
                      setState(() { insuranceCategory = newValue; });
                      print(newValue);
                    },
                 //  value: insuranceCategory,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(10, 10, 10,0),
                  child: RaisedButton(
                    onPressed: () {
                      contact();
                    },
                    child: Text('Submit'),
                  ),
                )
              ],
            ),
          )
      ),
    );
  }

  getCategories() async{
    var resp = await 
    http.get('http://192.168.4.101:3000/category/getCategoryList');
    print(resp.body);
    insCat = json.decode(resp.body);
    setState(() {
      insuranceCategory=insCat[0]['name'];
    });
  }
}

This is what the API is returning.

[
   {"_id":"5d8dad3a2fcb272b7c0e74b5","name":"life insurance"},
   {"_id":"5d8dad502fcb272b7c0e74b6","name":"vehicle insurance"},
   {"_id":"5d8dadb22fcb272b7c0e74b9","name":"life insurance"}
]
like image 892
sreeya chowdary Avatar asked Oct 09 '19 04:10

sreeya chowdary


1 Answers

Output:

enter image description here

void main() => runApp(MaterialApp(
      title: "Hospital Management",
      home: MyApp(),
    ));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _mySelection = "2";
  final String url = "http://webmyls.com/php/getdata.php";
  List data = List(); //edited line
  List<DropdownMenuItem> items = [];

  Future<String> getSWData() async {
    var res = await http.get(Uri.encodeFull(url), headers: {"Accept": "application/json"});
    var resBody = json.decode(res.body);

    setState(() {
      data = resBody;
      items = data.map((item) => DropdownMenuItem(child: Text(item['item_name']), value: item['id'].toString())).toList();
      _mySelection = data[0]["id"];
    });
    print(resBody);
    return "Sucess";
  }

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

  @override
  Widget build(BuildContext context) {
    print("CoolTag: ${data.length}");
    return Scaffold(
      appBar: AppBar(title: Text("Hospital Management")),
      body: Center(
        child: DropdownButton(
          items: items,
          value: _mySelection,
          onChanged: (newVal) {
            setState(() {
              _mySelection = newVal;
            });
          },
        ),
      ),
    );
  }
}
like image 167
CopsOnRoad Avatar answered Oct 18 '22 20:10

CopsOnRoad