How can I make dropdownbutton using Getx in flutter?

Issue

I’m trying to make dropdownbutton using Getx in flutter
However, it doesn’t work.
Even if I choose a value, the value does not been selected.


class BecomePlayerPage2 extends GetView<BecomePlayerController> {
  const BecomePlayerPage2 ({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(
          () => Scaffold(
        body: Padding(
          padding: EdgeInsets.all(20),
          child:
              DropdownButton<RxString>(
                onChanged: (newValue){
                  controller.selected=newValue!;
                },
                value: controller.selected,
                items: [
                  for(var value in controller.tierList)
                    DropdownMenuItem(
                        child: new Text(
                          value,
                        ),
                    value: value.obs,
                    ),
                ]

              ),
          ),
        ),   
}

class BecomePlayerController extends GetxController {

  final tierList=['first', 'second', 'third'].obs;
  var selected = "first".obs;



}

This is my first day of studying Getx so it is so hard to match with basic widget.
What should I do?

Solution

Try replacing the onChange statement with

onChanged: (newValue) {
   controller.selected.value = newValue.toString();
},

or by changing Dropdown button type from RXString to String

return Obx(
  () => Scaffold(
    body: Padding(
      padding: const EdgeInsets.all(20),
      child: DropdownButton<String>( // updated
          onChanged: (newValue) {
            controller.selected.value = newValue!; //updated
          },
          value: controller.selected.value, //updated
          items: [
            for (var value in controller.tierList)
              DropdownMenuItem(
                value: value, 
                child: Text(
                  value, //updated
                ),
              ),
          ]),
    ),
  ),
);

Answered By – Paulo

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *