Search code examples
jsonlistdartflutterdropdown

How to load local Json to Flutter DropDown based on other dropdown selection?


I have a local json file and based on the Company name and/or branch name I need to load them in 2 different dropdown list in Flutter.

1) Company DropDown: It will contain/shows List of CompanyName with CompanyCode like;

Example: Company A(01)

2) Branch DropDown: It will contain/shows List of BranchName with BranchCode based on selected Company name like;

Example: First Branch (0001)

My question is I can load local Json file and add to Map but how can I add to List so I can load with dropdown in Flutter?

{  
   "branch":[  
      {  
         "companyCode”:”01”,
         "companyName”:”Comapmy A”,
         "branchCode”:”0001”,
         "branchName”:”First Branch“
      },
      {  
         "companyCode”:”01",
         "companyName”:”Company A”,
         "branchCode”:”0002”,
         "branchName”:”Second Branch”
      },
      {  
         "companyCode”:”02”,
         "companyName”:”Company B”,
         "branchCode”:”0001”,
         "branchName”:”First Branch”
      }
   ]
}


String jsonCompany = await rootBundle.loadString("packages/capi/company.json");
Map _mapCompnay = jsonDecode(jsonCompany);

Solution

  • Here you have the json Object:

    Map _mapCompany = jsonDecode(jsonCompany);
    

    Next , get the array from branch object :

    List list = _mapCompany["branch"]; 
    

    that's all , now you can use your list to fill your DropDown:

            DropdownButton<String>(
                          items:list.map((Map val){
                            return DropdownMenuItem<String>(
                              value: val["companyCode"],
                              child: new Text(val["companyName"]),
                            );
                          }).toList(),
                          ...