【问题标题】:How can I add a button inside a dropdownButton in Flutter如何在 Flutter 的 dropdownButton 中添加按钮
【发布时间】:2021-11-08 00:04:42
【问题描述】:

我刚开始学习flutter,之前有编程知识,但是刚刚习惯了widget的结构。我想要做的是向 DropdownButton 列表的最后一个元素添加一个按钮,我使用 DropdownMenuItem 小部件来做到这一点。我使用 Text 作为子元素,并将 Button 放在最后一个元素中。问题是,我无法将 Text 赋予 DropdownButton 的 value 属性。这就是我收到错误的原因,因为我给出的值不在项目 [] 中。有什么方法可以获取 Text 小部件的值吗?或者我可以用其他方式吗?我希望我是解释性的。

代码:

class _TodoPageState extends State<TodoPage> {
  Text dropdownValue = Text('123'); // **FOR DEFAULT VALUE**

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Center(
      child: Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        // crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          MyTabBar(),
          Row(
            children: [
              Expanded(
                child: Container(
                  margin: EdgeInsets.only(left: 3, top: 5),
                  child: Row(
                    children: [
                      Ink(
                        width: 152,
                        height: 45,
                        padding: EdgeInsets.all(6),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.black, width: 2),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: DropdownButtonHideUnderline(
                          child: DropdownButton<String>(
                            value: dropdownValue, **// CANT SET THE DEFAULT VALUE**
                            isExpanded: true,
                            icon: Image.asset('assets/down-list-arrow.png'),
                            iconSize: 10,
                            elevation: 16,
                            onChanged: (newValue) {
                              setState(() {
                                dropdownValue = newValue!; **// CANT SET THE DEFAULT VALUE** 
                              });
                            },
                            items: [
                              DropdownMenuItem(child: Text('123'), value: ''),
                              DropdownMenuItem(child: Text('123'), value: ''),
                              DropdownMenuItem(
                                  child: TextButton(
                                child: Text('Create'),
                                onPressed: () {},
                              ))
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
          MyListView()
        ],
      ),
    ));
  }
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    我找到了 2 种方法:在值上分配 create 或在分配 onChanged 和使用 FocusNode 之前检查新值。

    测试小部件

    class TodoPage extends StatefulWidget {
      TodoPage({Key? key}) : super(key: key);
    
      @override
      _TodoPageState createState() => _TodoPageState();
    }
    
    class _TodoPageState extends State<TodoPage> {
      late String selectedValue; // **FOR DEFAULT VALUE**
      late String selectedValue2;
      List<String> dropDownItemValue = ['123', '2', '4', 'Create'];
      List<String> dropDownItemValue2 = ['xx', '2', '4'];
    
      late final dropDownKey2;
    
      final FocusNode dropDownFocus = FocusNode();
    
      @override
      void initState() {
        super.initState();
    
        ///selected value must be contain at dropDownItemValue
        selectedValue = dropDownItemValue[0];
        selectedValue2 = dropDownItemValue2[0];
      }
    
      @override
      Widget build(BuildContext context) {
        return SafeArea(
            child: Scaffold(
          backgroundColor: Colors.deepPurple,
          body: Center(
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.center,
              // crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // MyTabBar(),
    
                DropdownButtonHideUnderline(
                  child: DropdownButton<String>(
                    value: selectedValue, // CANT SET THE DEFAULT VALUE**
                    isExpanded: true,
                    // icon: Image.asset('assets/down-list-arrow.png'),
                    iconSize: 10,
                    elevation: 16,
                    onChanged: (newValue) {
                      print(newValue);
                      setState(() {
                        selectedValue = newValue!; //   SET THE DEFAULT VALUE**
                      });
                    },
    
                    /// dont assing same value on multiple widget
                    items: List.generate(
                      dropDownItemValue.length,
                      (index) => DropdownMenuItem(
                          child: Text('${dropDownItemValue[index]}'),
                          value: '${dropDownItemValue[index]}'),
                    ),
                  ),
                ),
    
                SizedBox(
                  height: 100,
                ),
                DropdownButtonHideUnderline(
                  child: DropdownButton<String>(
                    focusNode: dropDownFocus,
                    value: selectedValue2, // CANT SET THE DEFAULT VALUE**
                    isExpanded: true,
                    // icon: Image.asset('assets/down-list-arrow.png'),
                    iconSize: 10,
                    elevation: 16,
                    onChanged: (newValue) {
                      print(newValue == null);
                      // if value doesnt contain just close the dropDown
                      if (newValue == null) {
                        dropDownFocus.unfocus();
                      } else
                        setState(() {
                          selectedValue2 = newValue; //   SET THE DEFAULT VALUE**
                        });
                    },
    
                    /// dont assing same value on multiple widget
                    items: List.generate(
                      dropDownItemValue2.length + 1,
                      (index) => index < dropDownItemValue2.length
                          ? DropdownMenuItem(
                              child: Text('${dropDownItemValue2[index]}'),
                              value: '${dropDownItemValue2[index]}')
                          : DropdownMenuItem(
                              child: TextButton(
                                child: Text('Create'),
                                onPressed: () {},
                              ),
                            ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
      }
    }
    

    【讨论】:

    • 当我检查你的代码时,我更好地理解了逻辑以及实际上需要做什么,而第一个解决方案正是我想要的。非常感谢!
    • 很高兴你能帮到你。
    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2023-02-24
    • 2020-04-07
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2021-01-17
    相关资源
    最近更新 更多