Dart Flutter

Dependent dropdown flutter

Hello friend , In this chapter, I am going to teach you how to add dependent dropdown feature in Flutter. dropdown feature I think that if someone is making an app which is user friendly then it is necessary to add dropdown feature and if you want to show simple data then you can use simple drop down Well that’s a different matter , If you have searched this page then you have come for the drop down only.

So let’s get started:

I am making this chapter here with a simple example, Like take an example which will have country, state and city whenever a user select the any country. So all the states of that country will be displayed. And when the user selects the state, all the cities of that state will be displayed.

For the drop down, we will use a  Map object of three, which will have the value of k as you see below.

Note: The Map object is a simple key/value pair. 

Example

void main() { 
   var details = {'Usrname':'learncodezone','Password':'pass@123'}; 
   details['Uid'] = 'U1oo1'; 
   print(details); 
} 

The Map object we will use will be three for Country State and City. So you can see the map object of Country, State and Cities one by one below.

Country

var country={'India':'IN','Pakistan':'PAK','Nepal':'NP','Bangladesh':'BD'};

State

var state={'Jharkhand':'IN','Panjab':'IN','Baluchistan':'PAK','Dhaka':'BD','Janakpur':'NP'};

City

var city={'Ranchi':'Jharkhand','Tata':'Jharkhand','Quetta':'Baluchistan','Ludhiana':'Panjab','Amritsar':'Panjab'};

Did you see anything up?

Here, if you look in the state, you will find Here the value of each state defines this country. In the same way, now look at the city variable, here also every city defines its state. So you can see here how here is a dataset link with another dataset.

Now if I will ask you, looking at the above three datasets, tell which state belongs to which country and how many cities are there inside that state. Now if I will ask you, looking at the above three datasets, tell which state belongs to which country and how many cities are there inside that state.

Like which state is inside India and which city is it?

JharkhandRanchi
Tata
India
PanjabAmritsar
Ludhiana

So I think now you have understood its logic. And if you want to understand with more large dataset then click here

So now we need to create a drop down so that we can display this data here.

Now we make a method for the country

 String _selectedCountry="India";
 var country={'India':'IN','Pakistan':'PAK','Nepal':'NP','Bangladesh':'BD'};

 List _countries=[];
 CountryDependentDropDown(){
   country.forEach((key, value) {
     _countries.add(key);
   });
 }

Here I have set the default to a country in a variable(_selectedCountry), And in the _countries I just put new map

Now we can show it in drop down

Container(
              width: 400,
              child: DropdownButton(
                value: _selectedCountry,
                onChanged: (newValue){
                  setState(() {
                    _selectedCountry="$newValue";
                  });

                },
                items:_countries.map((country){
                  return DropdownMenuItem(
                    child: new Text(country),
                    value:country,
                  );
                }).toList(),
              ),
            ),

You will find in the above method that when the user changes the country, the setState method will replace the default value to selected value .

And we will send the state[ StateDependentDropDown() ] method to the country changed by the user. Like this :

 Container(
              width: 400,
              child: DropdownButton(
                value: _selectedCountry,
                onChanged: (newValue){
                  setState(() {
                      StateDependentDropDown(country[newValue]);
                    _selectedCountry="$newValue";
                  });

                },
                items:_countries.map((country){
                  return DropdownMenuItem(
                    child: new Text(country),
                    value:country,
                  );
                }).toList(),
              ),
            ),

and the StateDependentDropDown method is Like this :

 String _selectedState="";
 var state={'Jharkhand':'IN','Panjab':'IN','Baluchistan':'PAK','Dhaka':'BD','Janakpur':'NP'};

 List _states=[];
 StateDependentDropDown(countryShortName){
   state.forEach((key, value) {
     if(countryShortName==value){
       _states.add(key);
     }

   });
   _selectedState= _states[0];
 }

Now here you can see that in a loop I have added a condition that the country the user has selected, only the state of that county will be added to the Map object containing the _states.

  if(countryShortName==value){
       _states.add(key);
     }

So now after filtering the country’s accounting states, you can display them in the drop down.

 Container(
              width: 400,
              child: DropdownButton(
                value: _selectedState,
                onChanged: (newValue){
                  print(newValue);
                  setState(() {
                    print(newValue);
                    _cities=[];
                    CityDependentDropDown(newValue);

                   _selectedState="$newValue";
                  });

                },
                items:_states.map((state){
                  return DropdownMenuItem(
                    child: new Text(state),
                    value:state,
                  );
                }).toList(),
              ),
            ),

And then the same process will be done for the filter of cities

Full Code :

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dependent DropDown',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Dependent DropDown'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);


  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
 String _selectedCountry="India";
 var country={'India':'IN','Pakistan':'PAK','Nepal':'NP','Bangladesh':'BD'};

 List _countries=[];
 CountryDependentDropDown(){
   country.forEach((key, value) {
     _countries.add(key);
   });
 }

 String _selectedState="";
 var state={'Jharkhand':'IN','Panjab':'IN','Baluchistan':'PAK','Dhaka':'BD','Janakpur':'NP'};

 List _states=[];
 StateDependentDropDown(countryShortName){
   state.forEach((key, value) {
     if(countryShortName==value){
       _states.add(key);
     }

   });
   _selectedState= _states[0];
 }

 String _selectedCity="";
 var city={'Ranchi':'Jharkhand','Tata':'Jharkhand','Quetta':'Baluchistan','Ludhiana':'Panjab','Amritsar':'Panjab'};

 List _cities=[];
 CityDependentDropDown(stateShortName){
   city.forEach((key, value) {
     if(stateShortName==value){
       _cities.add(key);
     }

   });
   _selectedCity= _cities[0];
 }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    CountryDependentDropDown();
  }
  @override

  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        margin:EdgeInsets.all(15),

        child: Column(

          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            SizedBox(height: 23,),
          Align(
           alignment: Alignment.centerLeft,
           child:Text("Country",  style: TextStyle(fontWeight:FontWeight.bold,fontSize: 18),),
          ),
            Container(
              width: 400,
              child: DropdownButton(
                value: _selectedCountry,
                onChanged: (newValue){
                  setState(() {
                    _cities=[];
                    _states=[];
                    StateDependentDropDown(country[newValue]);
                    _selectedCountry="$newValue";
                  });

                },
                items:_countries.map((country){
                  return DropdownMenuItem(
                    child: new Text(country),
                    value:country,
                  );
                }).toList(),
              ),
            ),
            SizedBox(height: 23,),

          Align(
            alignment: Alignment.centerLeft,
            child:Text("State", style: TextStyle(fontWeight:FontWeight.bold,fontSize: 18),)
          ),
            Container(
              width: 400,
              child: DropdownButton(
                value: _selectedState,
                onChanged: (newValue){
                  print(newValue);
                  setState(() {
                    print(newValue);
                    _cities=[];
                    CityDependentDropDown(newValue);

                   _selectedState="$newValue";
                  });

                },
                items:_states.map((state){
                  return DropdownMenuItem(
                    child: new Text(state),
                    value:state,
                  );
                }).toList(),
              ),
            ),
            SizedBox(height: 23,),

            Align(
                alignment: Alignment.centerLeft,
                child:Text("City", style: TextStyle(fontWeight:FontWeight.bold,fontSize: 18),)
            ),
            Container(
              width: 400,
              child: DropdownButton(
                value: _selectedCity,
                onChanged: (newValue){
                  setState(() {
                    _selectedCity="$newValue";
                  });

                },
                items:_cities.map((city){
                  return DropdownMenuItem(
                    child: new Text(city),
                    value:city,
                  );
                }).toList(),
              ),
            )


          ],
        ),
      ),
    // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Output

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published. Required fields are marked *