Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter DropdownButton widget with Getx

I'm in the process of learning GetX state management and stumble upon the DropdownButton widget. How do I update the selected value with the selected value cannot be observed. Here is my DropdownButton widget

              DropdownButton(
                  hint: Text(
                    'Book Type',
                  ),
                  onChanged: (newValue) {
                    print(newValue);
                  },
                  value: selectedType,
                  items: bookController.listType.map((selectedType) {
                    return DropdownMenuItem(
                      child: new Text(
                        selectedType,
                      ),
                      value: selectedType,
                    );
                  }).toList(),
                ),

The

var selectedType;

declared in the widget build. I tried to make this variable observable but the layout throws an overflow error. I also wrap the widget with obx but still, it throws the same error. How do exactly this widget implement using GetX. I'm pulling my hair here. I can work with other widgets with getX.

like image 732
Hanis Avatar asked Jan 24 '23 10:01

Hanis


1 Answers

First create your controller class.

class BookController extends GetxController {

   // It is mandatory initialize with one value from listType
   final selected = "some book type".obs;

   void setSelected(String value){
     selected.value = value;
   }

}

On the view, instantiate your Controller and wrap the DropdownButton with an Obx widget:

    BookController bookcontroller = BookController();
    
    Obx( () => DropdownButton(
                      hint: Text(
                        'Book Type',
                      ),
                      onChanged: (newValue) {
                        bookController.setSelected(newValue);
                      },
                      value: bookController.selected.value,
                      items: bookController.listType.map((selectedType) {
                        return DropdownMenuItem(
                          child: new Text(
                            selectedType,
                          ),
                          value: selectedType,
                        );
                      }).toList(),
                    )
),
like image 100
djalmafreestyler Avatar answered Jan 31 '23 02:01

djalmafreestyler