0

I am trying to put a DropdownButton on one of my screens. I have followed several examples but I can not get it to show the selected item. It keeps showing the first item in the list.

String _trxnStatus = 'Listed';

DropdownButton<String>(
                hint: Text('Please choose transaction status'),
                value: _trxnStatus,
                onChanged: (value) {
                  setState(() {
                    _trxnStatus = value;
                  });
                },
                items: <String>['Listed', 'Under Contract', 'Closed'].map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              ),

I have traced the value through the debugger. onChange works fine and shows the selected value. However, when it comes to mapping the list and returning the DropdownMenuItem the var value = 'Listed'.

How do I get this to work? Thanks.

RaSha
  • 1,356
  • 1
  • 16
  • 30
LostTexan
  • 431
  • 5
  • 18

1 Answers1

2

You are possibly initializing the _trxnStatus within the build function. You need to initialize _trxnStatus outside of the build function. Please see the working code below:

import 'package:flutter/material.dart';

final Color darkBlue = const Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String _trxnStatus = 'Listed';
  @override
  Widget build(BuildContext context) {
    return DropdownButton<String>(
      hint: Text('Please choose transaction status'),
      value: _trxnStatus,
      onChanged: (value) {
        setState(() {
          _trxnStatus = value;
        });
      },
      items: <String>['Listed', 'Under Contract', 'Closed']
          .map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }
}
bluenile
  • 5,673
  • 3
  • 16
  • 29