带有 Getx 的 Flutter DropdownButton 小部件

Han*_*nis 2 flutter dropdownbutton getx

我正在学习 GetX 状态管理并偶然发现 DropdownButton 小部件。无法观察到如何使用所选值更新所选值。这是我的 DropdownButton 小部件

              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(),
                ),
Run Code Online (Sandbox Code Playgroud)

var selectedType;
Run Code Online (Sandbox Code Playgroud)

在小部件构建中声明。我试图使这个变量可观察,但布局会引发溢出错误。我也用 obx 包装了小部件,但它仍然抛出相同的错误。这个小部件是如何使用 GetX 实现的。我在这里拉头发。我可以使用 getX 处理其他小部件。

dja*_*ler 6

首先创建您的控制器类。

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;
   }

}
Run Code Online (Sandbox Code Playgroud)

在视图上,实例化您的控制器并使用 Obx 小部件包装 DropdownButton:

    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(),
                    )
),
Run Code Online (Sandbox Code Playgroud)

  • 我收到以下错误以下断言在构建 Obx(dirty, state: _ObxState#829ce): 时抛出了以下断言:应该只有一项具有 [DropdownButton] 的值: 。检测到零个或 2 个或多个 [DropdownMenuItem] 具有相同的值 'package:flutter/src/material/dropdown.dart': 断言失败: line 850 pos 15: 'items == null || items.isEmpty || 值==空|| items.where((DropdownMenuItem<T> 项目) { (3认同)