Flutter: Selected value in dropdown list

nypogi picture nypogi · Jul 24, 2018 · Viewed 13.2k times · Source

The initial value in the dialog box doesn't change when I select an item. Here is the code for the dropdown list:

void _buildStatusDialog(String documentID) {
String _selectedText = "SDD";
showDialog<void>(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text("Status Update"),
        content: new DropdownButton<String>(
          hint: Text("Status"),
          value: _selectedText,
          items: <String>['SDD', 'Meeting', 'Home', 'Space']
              .map((String value) {
            return new DropdownMenuItem<String>(
              value: value,
              child: new Text(value),
            );
          }).toList(),
          onChanged: (String val) {
            _selectedText = val;
            setState(() {
              _selectedText = val;
            });
          },
        ),
        actions: <Widget>[
          FlatButton(
            child: Text("UPDATE"),
            onPressed: () {
              .....
            },
          ),
        ],
      );
    });

}

How do I update the "hint" or display the selected item?

enter image description here

Answer

AXE picture AXE · Oct 25, 2019

Using @Jonah Williams's tip in the comments I came up with the following working example to a similar problem that I had:

import 'package:flutter/material.dart';

class StatusDialog extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return StatusDialogState();
  }
}

class StatusDialogState extends State<StatusDialog> {
  String _selectedText = "SSD";

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text("Status Update"),
      content: new DropdownButton<String>(
        hint: Text("Status"),
        value: _selectedText,
        items: <String>['SDD', 'Meeting', 'Home', 'Space']
            .map((String value) {
          return new DropdownMenuItem<String>(
            value: value,
            child: new Text(value),
          );
        }).toList(),
        onChanged: (String val) {
          setState(() {
            _selectedText = val;
          });
        },
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("UPDATE"),
          onPressed: () {
            //.....
          },
        ),
      ],
    );
  }
}

void _buildStatusDialog(String documentID) {
  showDialog<void>(
    context: context,
    builder: (BuildContext context) {
      return StatusDialog();
    }
  );
}

Then you just need to add some logic to obtain _selectedText from StatusDialog - probably using a callback.