How to Add DropdownButton Items with Array List in Flutter

In this example, we are going to show you the easiest way to implement the dropdown button and add Menu Items from array List. We also show you the way to select value, set the initial value. See the example. 

Read This Also: How to add Dropdown Button Widget in Flutter App

List<String> listitems = ["United States of America", "Canada", "United Kingdom", "China", "Russia", "Austria"];
String selectval = "United States of America";

DropdownButton(
    value: selectval,
    onChanged: (value){
        setState(() {
          selectval = value.toString();
        });
    },
    items: listitems.map((itemone){
        return DropdownMenuItem(
          value: itemone,
          child: Text(itemone)
        );
    }).toList(),
)

Here, selectval will be the selected item, you can use this variable while submitting your form.

If you encounter any error, have a look at How to Solve DropdownButton Errors in Flutter

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp( home: MyApp(),)
  );
}

class MyApp extends StatefulWidget{
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  List<String> listitems = ["United States of America", "Canada", "United Kingdom", "China", "Russia", "Austria"];
  String selectval = "United States of America";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("Dropdown Button in Flutter"),
              backgroundColor: Colors.deepOrange,
          ),
          body: Container( 
              margin: EdgeInsets.only(top:80),
              alignment: Alignment.topCenter,
              child: DropdownButton(
                  value: selectval,
                  onChanged: (value){
                     setState(() {
                        selectval = value.toString();
                     });
                  },
                  items: listitems.map((itemone){
                      return DropdownMenuItem(
                        value: itemone,
                        child: Text(itemone)
                      );
                  }).toList(),
              ),
          )
      );
  }
}

In this way, you can add DropdownButton widget and populate Items from List Array in Flutter.

No any Comments on this Article


Please Wait...