'Try to filter data from JSON in Flutter Custom Drop Down menu

I am trying to filter data from JSON in CustomDropDownMenu. I can acceess the data from JSON. But I want to do it like this, when the user choose the Course 1, I'm trying to fetch specilities with course id 1 from json. I hope I explained clearly. Could you please help me? thanks in advance

Here is my DropDownWidget that I used. According to the incoming list, it prints the elements in that list.

class CustomDropDown extends StatefulWidget {
  List itemList;
  String hintText;

  CustomDropDown(this.itemList, this.hintText, {Key? key}) : super(key: key);

  @override
  _CustomDropDownState createState() => _CustomDropDownState();
}

class _CustomDropDownState extends State<CustomDropDown> {
  late String dropdownValue;
  @override
  void initState() {
    if (widget.itemList is List<Course>) {
      dropdownValue = widget.itemList[0].courseName;
    } else if (widget.itemList is List<String>) {
      dropdownValue = widget.itemList[0];
    } else if (widget.itemList is List<Speciality>) {
      dropdownValue = widget.itemList[0].name;
    } else if (widget.itemList is List<Institute>) {
      dropdownValue = widget.itemList[0].instituteName;
    } else if (widget.itemList is List<AttendingPhysician>) {
      dropdownValue = widget.itemList[0].attendingName;
    }
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(4),
      child: Column(
        children: [
          Text(
            widget.hintText,
            style: TEXT_STYLE,
          ),
          Padding(
            padding: const EdgeInsets.all(PADDING_VALUE),
            child: Container(
              height: 50,
              decoration: BoxDecoration(
                  color: Colors.grey[700],
                  borderRadius: BorderRadius.circular(5)),
              child: DropdownButtonFormField<String>(
                decoration: const InputDecoration(border: InputBorder.none),
                isExpanded: true,
                validator: (val) => val == null || val.isEmpty
                    ? 'Lütfen ${widget.hintText} giriniz'
                    : null,
                value: dropdownValue,
                icon: const Icon(
                  Icons.arrow_downward,
                  color: ICON_COLOR,
                ),
                iconSize: 24,
                elevation: 16,
                dropdownColor: Colors.grey[800],
                style: TEXT_STYLE,
                onChanged: (val) {
                  print("dropdown aaa");
                  print(val.toString());
                  setState(() {
                    dropdownValue = val!;
                  });
                },
                items: widget.itemList
                    .map<DropdownMenuItem<String>>((dynamic val) {
                  String text = "";
                  if (val is Course) {
                    text = val.courseName;
                  } else if (val is AttendingPhysician) {
                    text = val.attendingName;
                  } else if (val is String) {
                    text = val;
                  } else if (val is Speciality) {
                    text = val.name;
                  } else if (val is Institute) {
                    text = val.instituteName;
                  } else if (val is AttendingPhysician) {
                    text = val.attendingName;
                  }
                  return DropdownMenuItem<String>(
                    value: text,
                    child: Center(
                      child: Text(
                        text,
                        style: TEXT_STYLE,
                      ),
                    ),
                  );
                }).toList(),
              ),
            ),
          )
        ],
      ),
    );
  }
}

Courses JSON data

[
    {
        "id": 1,
        "name": "Course1"
    },
    {
        "id": 2,
        "name": "Course2"
    },
    {
        "id": 3,
        "name": "Course3"
    }
]

Specilities JSON data

[
    {
        "id": 3,
        "description": "Speciality1",
        "course": {
            "id": 1,
            "name": "Course1"
        }
    }
]

Fetch from database

Future<List<Course>> fetchCourses() async {
    var url = Uri.parse("${DBURL.url}/courses");
    var response = await http.get(url);

    if (response.statusCode == 200) {
      List<dynamic> data = jsonDecode(response.body);
      List<Course> courses = data.map((e) => Course.fromJSON(e)).toList();
      return courses;
    } else {
      throw Exception('Failed to load ');
    }
  }

  Future<List<Speciality>> fetchSpeciality() async {
    var url = Uri.parse("${DBURL.url}/specialities?courseId=1");
    var response = await http.get(url);

    if (response.statusCode == 200) {
      List<dynamic> data = jsonDecode(response.body);
      List<Speciality> speciality =
          data.map((e) => Speciality.fromJSON(e)).toList();
      return speciality;
    } else {
      throw Exception('Failed to load ');
    }
  }

Main Class

return Scaffold(
      body: SafeArea(
          child: FutureBuilder(
              future: fetchFormContent(), //readJsonData(),
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  return const Center(
                      child: Text("Oops! Something went wrong."));
                } else if (snapshot.hasData) {
                  var listOfContent = snapshot.data as dynamic;
                  var courses = listOfContent[0];
                  var specialities = listOfContent[1];
                  var institutes = listOfContent[2];
                  var attendings = listOfContent[3];


                  Map<String, dynamic> map = {
                    'course': courses,
                    'etkilesim': listOfEtkilesimTuru,
                    'kapsam': listOfKapsam,
                    'ortam': listOfOrtam,
                    'specialities': specialities,
                    'institutes': institutes,
                    'attendings': attendings,
                    'cinsiyet': listOfCinsiyet,
                  };
                  return isLoading ? spinkit : formWidget(map);
                } else {
                  return Center(
                    child: spinkit,
                  );
                }
              })),
Form formWidget(Map<String, dynamic> map) {
    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        child: Column(
          //  shrinkWrap: true,
          children: [
            CustomDropDown(map['course'], "Courses"),
            CustomDropDown(map['specialities'], "Speciality"),
        
        ),
      ),
    );
  }

  Future<List<List<dynamic>>> fetchFormContent() async {
    List<List<dynamic>> res = [];

    List<Course> courses = await _dbHelper.fetchCourses();
    List<Speciality> speciality = await _dbHelper.fetchSpeciality();
    List<Institute> institute = await _dbHelper.fetchInstitute();
    List<AttendingPhysician> attendings =
        await _dbHelper.fetchAttendingPhysicians();

    res.add(courses);
    res.add(speciality);
    res.add(institute);
    res.add(attendings);

    return res;
  }

Class of Specilities and Courses

import 'package:internship_managing_system/model/Course.dart';

class Speciality {
  int id;
  String name;
  Course course;

  Speciality({required this.id, required this.name, required this.course});

  factory Speciality.fromJSON(Map<String, dynamic> map) {
    return Speciality(
        id: map['id'],
        name: map['description'],
        course: Course.fromJSON(map['course']));
  }
}

class Course {
  int id;
  String courseName;

  Course({required this.id, required this.courseName});

  factory Course.fromJSON(Map<String, dynamic> map) {
    return Course(id: map['id'], courseName: map['name']);
  }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source