Flutter: Everything you need to know Dropdown

Most of the app in the world requires dropdown and at least for one or two times. Sometimes for Language change feature and sometimes for selecting one option from long list of data

I have one article about multi level dropdown and it’s one step ahead of this. If you don’t have good understanding of dropdown then you should read this before heading towards it.

Get Started

How dropdown works?

I am not sure how much you understand the dropdown but in order to make multi level dropdown you need to understand the dropdown properly.

Label Description
hint This value will be shown when no value is selected.
value This value will be shown as selected
items It look for list of DropdownMenuItem widget.
onChanged It is callback and it being called with the value of DropdownButton

You might have notice I have wrote String 5 times. This depends on the value of DropdownButton. It can be anything and every time we are not going to get string. So, it’s important how to work with generic while using DropdownButton.

One more important thing it’s not mandatory to use value and child text as same. Let’s see one more example to understand this.

This is going to be the simples example of the dropdown. The purpose of this example is make you understand the basic of dropdown.

If you understand this example then probably you will understand all the further example easily.

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

class ExampleScreen extends StatefulWidget {
  @override
  _ExampleScreenState createState() => _ExampleScreenState();
}

class _ExampleScreenState extends State<ExampleScreen> {
  String selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Example 1'),
      ),
      body: Center(
        child: DropdownButton<String>(
          hint: Text('Country'),
          value: selectedCountry,
          items: <DropdownMenuItem<String>>[
            DropdownMenuItem<String>(
              value: 'USA',
              child: Text('USA'),
            ),
            DropdownMenuItem<String>(
              value: 'India',
              child: Text('India'),
            ),
          ],
          onChanged: (String country) {
            print('You selected "$country"');
            setState(() {
              selectedCountry = country;
            });
          },
        ),
      ),
    );
  }
}

In this example, I will have different value and child text string. This example will not have String as generic, I am using int here.

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

class ExampleScreen extends StatefulWidget {
  @override
  _ExampleScreenState createState() => _ExampleScreenState();
}

class _ExampleScreenState extends State<ExampleScreen> {
  int selectedNumber;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Example 2'),
      ),
      body: Center(
        child: DropdownButton<int>(
          hint: Text('Country'),
          value: selectedNumber,
          items: <DropdownMenuItem<int>>[
            DropdownMenuItem<int>(
              value: 1,
              child: Text('One'),
            ),
            DropdownMenuItem<int>(
              value: 2,
              child: Text('Two'),
            ),
          ],
          onChanged: (int value) {
            print('You selected "$value"');
            setState(() {
              selectedNumber = value;
            });
          },
        ),
      ),
    );
  }
}

In this example, we will use array and for creating DropdownMenuItem and this is something which will be used in most of the apps. This method simplifies the UI code and make is shorter too.

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

class ExampleScreen extends StatefulWidget {
  @override
  _ExampleScreenState createState() => _ExampleScreenState();
}

class _ExampleScreenState extends State<ExampleScreen> {
  final List<String> country = ['USA', 'India'];
  String selectedCountry;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Example 3'),
      ),
      body: Center(
        child: DropdownButton<String>(
          value: selectedCountry,
          hint: Text('Country'),
          items: country.map((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
          onChanged: (String value) {
            print('You selected "$value"');
            setState(() {
              selectedCountry = value;
            });
          },
        ),
      ),
    );
  }
}

In this dropdown then data is going to come from the internet. So, I have endpoint which I will hit and get the data. This dropdown is little advance because this uses a package called http for sending request to the network.

If you have not used the http package before then you should learn about that first. This example will not make any sense without the knowledge of http package.

four.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'custom_user.dart';  // Model Class

class ExampleScreen extends StatefulWidget {
  @override
  _ExampleScreenState createState() => _ExampleScreenState();
}

class _ExampleScreenState extends State<ExampleScreen> {
  final String endpoint =
      "https://raw.githubusercontent.com/nitishk72/flutter_json_list/master/json_example.json";
  List<CustomUser> users = [];
  CustomUser selectedUsers;

  @override
  void initState() {
    super.initState();
    loadDropdown();
  }

  Future<void> loadDropdown() async {
    final http.Response response = await http.get(endpoint);
    final String body = response.body;
    final jsonResponse = json.decode(body);
    users = jsonResponse
              .map((e) => CustomUser.fromJson(e))
              .toList();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Example 4'),
      ),
      body: Center(
        child: DropdownButton<CustomUser>(
          hint: Text('Country'),
          value: selectedUsers,
          isExpanded: true,
          items: users.map((CustomUser user) {
            return DropdownMenuItem<CustomUser>(
              value: user,
              child: Text('${user['name']}'),
            );
          }).toList(),
          onChanged: (CustomUser user) {
            setState(() {
              selectedUsers = user;
            });
            print("You selected \n ${user.toMap}");
          },
        ),
      ),
    );
  }
}
custom_user.dart
class CustomUser{
    final int id;
    final String name;
    final String email;
    final String address;

    CustomUser.fromJson(Map<String,dynamic> json):
        this.id = json['id'],
        this.name = json['name'],
        this.email = json['email'],
        this.address = json['address'];
    
    Map<String,dynamic> get toMap{
        return {
            'id' : this.id,
            'name' : this.name,
            'email' : this.email,
            'address' : this.address,
        };
    }
}

Now you have good understanding of dropdown and you should learn multi level. It’s something which is very important for building e-commerce or any school or bank kind of app.

Conclusion

In this article you learn about dropdown and I hope now you can work with dropdown which any issue.

If you have any suggestion or your like to ask anything then comment. I would love to answer to your queries.

Thank you