Search code examples
flutterlistdatatable

dynamic dropdown button with dynamic values from list in flutter


I have DataTable in flutter, which is dynamically created. I have one column which is filled with dropdown buttons, I am facing this out of Range Error.

Here is the code

List<String> _values = [
    "m\u00b3",
    "ft\u00b3",
    "cm\u00b3",
    "m\u00b2",
    "ft\u00b2",
    "cm\u00b2",
    "kg",
    "lb",
    "ton",
    "No\'s",
  ];
  List<String> _selectedValues = [];

here is the initState

  void initState() {
    super.initState();
    _selectedValues = List.generate(_values.length, (index) => _values[0]);
  }

Here is the data cell in which I am creating it dynamically,

DataCell(
       Container(
                child: DropdownButton(
            value: _selectedValues[index],
            items: _values
                .map((value) => DropdownMenuItem(
                      value: value,
                      child: Text(value),
                    ))
                .toList(),
            onChanged: (value) {
              setState(() {
                _selectedValues[index] = value!;
              });
            },
          ),)),

Here is the Error I am Getting,

Exception has occurred. RangeError (RangeError (index): Invalid value: Not in inclusive range 0..9: 10)

any help is highly appreciated.


Solution

  • I have added a List.genrate , so all the dropdown initial value would be different and also If you change value of one drop down it wont affect others

     List<String> _values = [
        "m\u00b3",
        "ft\u00b3",
        "cm\u00b3",
        "m\u00b2",
        "ft\u00b2",
        "cm\u00b2",
        "kg",
        "lb",
        "ton",
        "No\'s",
      ];
      List<String> _values2 = [
        "m\u00b3",
        "ft\u00b3",
        "cm\u00b3",
        "m\u00b2",
        "ft\u00b2",
        "cm\u00b2",
        "kg",
        "lb",
        "ton",
        "No\'s",
      ];
    

    the code

    List.generate(
          _values2.length,
          (index) => DataRow(
            cells: [
              DataCell(
                Container(
                  child: DropdownButton(
                    value: _values2[index],
                    items: _values
                        .map((value) => DropdownMenuItem(
                              value: value,
                              child: Text(value),
                            ))
                        .toList(),
                    onChanged: (value) {
                      setState(() {
                        _values2[index] = value.toString();
                      });
                    },
                  ),
                ),
              ),
            ],
          ),
        );