Download StackFood Multi Restaurant, Food Delivery App with Laravel Admin and Restaurant Panel Buy Full App on $79
Download FlutKit - Flutter UI Kit Most beautiful Flutter UI Kit with 20+ Full App, 450+ Screens. Buy Full Kit on $39
Download Fluxstore Multi Vendor WooCommerce/Dokan Plugin compatible WordPress eCommerce Flutter App. Buy Full App on $79

How to Fix Dropdown Button not Switching Selected Item in Flutter

When you implement the Dropdown Button with DropdownMenuItem, you may experience not switching of Items to Selected Value. In this example, we are going to show you the full working example of Dropdown Button in Flutter.

Step 1: Implement Dropdown Button in StatefulWidget:

First, you need to implement your widget build to StatefulWidget, because, you have to track the select value. You will not able to update app state or UI in StatelessWidget App.

Step 2: Implement Select Value and onChange property on DropdownButton Widget:

List<String> listitems = ["Tokyo", "London", "New York", "Sanghai", "Moscow", "Hong Kong"];
String selectval = "Tokyo";

DropdownButton(
    value: selectval, //implement initial value or selected value
    onChanged: (value){
        setState(() { //set state will update UI and State of your App
          selectval = value.toString(); //change selectval to new value
        });
    },
    items: listitems.map((itemone){
        return DropdownMenuItem(
          value: itemone,
          child: Text(itemone)
        );
    }).toList(),
)

Full Code Example:

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 = ["Tokyo", "London", "New York", "Sanghai", "Moscow", "Hong Kong"];
  String selectval = "Tokyo";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
          appBar: AppBar(
              title:Text("Dropdown Button in Flutter"),
              backgroundColor: Colors.deepPurpleAccent
          ),
          body: Container( 
              margin: EdgeInsets.only(top:50),
              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(),
              ),
          )
      );
  }
}

Output Screenshot:

In this way, you can switch newly selected value from current value on DropdownButton widget in Flutter.

No any Comments on this Article


Please Wait...