Khalifa Alkhatri
Khalifa Alkhatri

Reputation: 294

Why dropdownValue for DropdownButton not updated?

I did the steps in this link https://api.flutter.dev/flutter/material/DropdownButton-class.html but the String dropdownValue = 'One'; cant not be changed when I pressed 'Two' or "three or others buttons , nothing changes also setState notworking . can you help me ?

the full code is :

String dropdownValue = 'One';

@override
Widget build(BuildContext context) {
  return DropdownButton<String>(
    value: dropdownValue,
    icon: Icon(Icons.arrow_downward),
    iconSize: 24,
    elevation: 16,
    style: TextStyle(
      color: Colors.deepPurple
    ),
    underline: Container(
      height: 2,
      color: Colors.deepPurpleAccent,
    ),
    onChanged: (String newValue) {
      setState(() {
        dropdownValue = newValue;
      });
    },
    items: <String>['One', 'Two', 'Free', 'Four']
      .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      })
      .toList(),
  );
}

Upvotes: 0

Views: 60

Answers (1)

Sagar Acharya
Sagar Acharya

Reputation: 3767

From the above mentioned code i have just copy pasted it and it runs absolutely fine. Just check you are using the Statefull widget. As i have add the code below just check it out.

import 'package:flutter/material.dart';

main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
 String dropdownValue = 'One';

@override
Widget build(BuildContext context) {
  return MaterialApp(
      home: Scaffold(
              body: Center(
                              child: DropdownButton<String>(
        value: dropdownValue,
        icon: Icon(Icons.arrow_downward),
        iconSize: 24,
        elevation: 16,
        style: TextStyle(
          color: Colors.deepPurple
        ),
        underline: Container(
          height: 2,
          color: Colors.deepPurpleAccent,
        ),
        onChanged: (String newValue) {
          setState(() {
            dropdownValue = newValue;
          });
        },
        items: <String>['One', 'Two', 'Free', 'Four']
          .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
            );
          })
          .toList(),
    ),
              ),
      ),
  );
}
}

And i have also added the gif image to show you that the code is working perfectly.

enter image description here

Upvotes: 1

Related Questions