1

I want to create a seperate DropDown List for teacher name , class name and subject name. How can we do it?. I have written a code but it does not change dynamically while the name changes. I have included both my json response and dropdown code.

Here is my json response:

{
"status": {
    "code": 200,
    "message": "Success"
},
"data": {
    "message": "Fetched",
    "details": {
        "response": [
            {
                "teacher_id": "2222",
                "teacher_name": "abc",
                "details": [
                    {
                        "session_id": "123",
                        "class_id": "123",
                        "batch_id": "123",
                        "curriculum_id": "123",
                        "subjects": [
                            "123"
                        ],
                        "subject_details": [
                            {
                                "sub_id": "12222",
                                "sub_name": "science"
                            }
                        ],
                        "class_name": "10",
                        "batch_name": "D"
                    }
                ]
            },
            

I have written a code but it does not change dynamically while the name changes. here is my code:

DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: Container(
              child: DropdownButton(
                  value: teacherListSelected,
                  isExpanded: true,
                  hint: const Text(
                    'Teacher',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  onChanged: (String? newVal) {
                    setState(() {
                      this.teacherListSelected = newVal;
                      print(teacherListSelected);
                    });
                  },
                  items: teacherList?['response']
                      .map<DropdownMenuItem<String>>((item) {
                    return DropdownMenuItem<String>(
                      child: Text(item['teacher_name']),
                      value: item['teacher_id'],
                    );
                  }).toList()),
            ),
          ),
        ),
        DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: Container(
              child: DropdownButton(
                value: teacherClassSelected,
                isExpanded: true,
                hint: const Text(
                  'class',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                onChanged: (String? newVal) {
                  setState(() {
                    this.teacherClassSelected = newVal;
                    print(teacherClassSelected);
                  });
                },
                items: teacherList?['response'][1]['details']
                    .map<DropdownMenuItem<String>>((item) {
                  return DropdownMenuItem<String>(
                    child: Text(item['class_name']),
                    value: item['class_name'],
                  );
                }).toList()),
              ),
            ),
          ),
        DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: Container(
              child: DropdownButton(
                value: teacherSubjectSelected,
                isExpanded: true,
                hint: const Text(
                  'subject',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ), items: [],
                // onChanged: (String? newVal) {
                //   setState(() {
                //     this.teacherListSelected = newVal;
                //     getTeacherData();
                //     print(teacherListSelected);
                //   });
                // },
                // items: teacherList?['data']
                //     .map<DropdownMenuItem<String>>((item) {
                //   return DropdownMenuItem<String>(
                //     child: Text(item['teacher_name']),
                //     value: item['teacher_id'],
                //   );
                // }).toList()),
              ),
            ),
          ),
        ),
  • If you get data from API and display it into the drop-down refer my answer [here](https://stackoverflow.com/a/68418476/13997210) or [here](https://stackoverflow.com/a/68735915/13997210) and you can display drop-down menu inside other drop-down refer my answer [here](https://stackoverflow.com/a/68280926/13997210) hope it's helpful to you – Ravindra S. Patil Aug 15 '21 at 07:21
  • @RavindraS.Patil, I want to create a dependent dropdown from the same api response. –  Aug 15 '21 at 07:45

1 Answers1

0

There are two important things here:

  1. You have to save the array index of selected teacher and class as well, because this is how you can easily set the dependent dropdown items.
  2. You have to make sure you maintain consistency when selection changes. For example, if a class is already selected, and then another teacher is selected, it is important set the class selection to null, otherwise it would point to a class of another teacher, and Flutter would throw an error because this is no more in the dropdown value set.

Here is the code I think will work for, I made some assumptions, so maybe have to adjust it a little bit. I assume teacherList contains the values you posted like this:

final teacherList = (<String, dynamic>{
  "status": {"code": 200, "message": "Success"},
  "data": {
    "message": "Fetched init data",
    "details": {
      "response": [
        {
          "teacher_id": "2222",
          "teacher_name": "teacher 1",
          "details": [
(and so on)

Please find some comments in the code below:

// depending on Flutter version could be String?
Object? _teacherListSelected;
Object? _teacherClassSelected;
Object? _teacherSubjectSelected;
// these are the indexes of selected teacher / class
int? _teacherListSelectedIndex;
int? _teacherClassSelectedIndex;

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: const Text("My App"),
    ),
    body: Center(
      child: Column(children: [
        DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: Container(
              child: DropdownButton(
                  value: _teacherListSelected,
                  isExpanded: true,
                  hint: const Text(
                    'teacher',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  onChanged: (Object? newVal) {
                    setState(() {
                      _teacherListSelected = newVal;
                      // here we set the selected teacher's
                      // index in array as a number
                      _teacherListSelectedIndex =
                          int.parse(newVal.toString());

                      // every time a teacher is selected,
                      // set every other selection to null
                      _teacherClassSelected = null;
                      _teacherClassSelectedIndex = null;
                      _teacherSubjectSelected = null;
                    });
                  },
                  items: teacherList['data']['details']['response']
                      .map<DropdownMenuItem<String>>((item) {
                    return DropdownMenuItem<String>(
                      child: Text(item['teacher_name']),
                      // value will be the selected teacher's index
                      // in the array, stored as string
                      value: teacherList['data']['details']['response']
                          .indexOf(item)
                          .toString(),
                    );
                  }).toList()),
            ),
          ),
        ),
        DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: Container(
              child: DropdownButton(
                  value: _teacherClassSelected,
                  isExpanded: true,
                  hint: const Text(
                    'class',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  onChanged: (Object? newVal) {
                    setState(() {
                      _teacherClassSelected = newVal;
                      // here we save selected class array index
                      _teacherClassSelectedIndex =
                          int.parse(newVal.toString());
                      // set subject selection to null
                      _teacherSubjectSelected = null;
                    });
                  },
                  // if teacher is not selected, this list has to be empty
                  items: _teacherListSelected == null
                      ? null
                      // this is the part where class list is depending on
                      // selected teacher
                      : teacherList['data']['details']['response']
                              [_teacherListSelectedIndex]['details']
                          .map<DropdownMenuItem<String>>((item) {
                          return DropdownMenuItem<String>(
                            child: Text(item['class_name'] +
                                " " +
                                item['batch_name']),
                            // this is the index of the selected class
                            value: teacherList['data']['details']['response']
                                    [_teacherListSelectedIndex]['details']
                                .indexOf(item)
                                .toString(),
                          );
                        }).toList()),
            ),
          ),
        ),
        DropdownButtonHideUnderline(
          child: ButtonTheme(
            alignedDropdown: true,
            child: Container(
              child: DropdownButton(
                  value: _teacherSubjectSelected,
                  isExpanded: true,
                  hint: const Text(
                    'subject',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  onChanged: (Object? newVal) {
                    setState(() {
                      _teacherSubjectSelected = newVal;
                    });
                  },
                  // if class is not selected, subject list will be empty
                  items: _teacherClassSelected == null
                      ? null
                      // this is the part where subject list is depending on
                      // selected class
                      : teacherList['data']['details']['response']
                                  [_teacherListSelectedIndex]['details']
                              [_teacherClassSelectedIndex]['subject_details']
                          .map<DropdownMenuItem<String>>((item) {
                          return DropdownMenuItem<String>(
                            child: Text(item['sub_name']),
                            value: item['sub_id'],
                          );
                        }).toList()),
            ),
          ),
        ),
      ]),
    ),
  );
}
Peter Koltai
  • 8,296
  • 2
  • 10
  • 20