【问题标题】:How to change default value of dropdownButton in flutter?如何在颤动中更改下拉按钮的默认值?
【发布时间】:2021-12-16 19:19:27
【问题描述】:

我正在颤振中创建一个下拉按钮,但我有一个问题 当我使用下拉菜单时,它会显示 first item 的名称,但我想将其(默认值)更改为 categories 并且知道如何做到这一点,我也尝试使用提示(如您在代码中看到的),但它不起作用。 这是我的代码:

Container(
            height: pageHeight / 15,
            padding: EdgeInsets.all(20),
            child:DropdownButton(
                value: _value,
                items: const [
                  DropdownMenuItem(
                    child: Text("First Item"),
                    value: 1,
                  ),
                  DropdownMenuItem(
                    child: Text("Second Item"),
                    value: 2,
                  ),
                ],
                onChanged: (value) {
                  setState(() {
                    _value = value as int ;
                  });
                },
                hint:Text("Select item")
            ),
          )

我想将此 First Item 更改为 categories

【问题讨论】:

  • 你能说清楚一点吗?
  • 分享额外的代码,你到底想要什么
  • @ChinkySight 好的我编辑了

标签: flutter dart dropdownbutton


【解决方案1】:

使值可以为空。 DropdownButton 可以有 null 值,当它为 null 时,它将显示 hint 小部件。

  int? _value;
DropdownButton(
                  value: _value,
                  items: const [
                    DropdownMenuItem(
                      child: Text("First Item"),
                      value: 1,
                    ),
                    DropdownMenuItem(
                      child: Text("Second Item"),
                      value: 2,
                    ),
                  ],
                  onChanged: (value) {
                    setState(() {
                      _value = value as int;
                    });
                  },
                  hint: Text("categories"),
                ),

【讨论】:

  • 没错,我的价值是:int? _value=1;
  • 是的,它的初始值为 1,这就是为什么你总是选择第一个项目。
【解决方案2】:

只需在 initState() 上赋值

selectedDropDownValue = "类别";

Container(
            height: pageHeight / 15,
            padding: EdgeInsets.all(20),
            child:DropdownButton(
                value: _value,
                items: const [
                  DropdownMenuItem(
                    child: Text("First Item"),
                    value: 1,
                  ),
                  DropdownMenuItem(
                    child: Text("Second Item"),
                    value: 2,
                  ),
                ],
                value: selectedDropDownValue, 
                onChanged: (value) {
                  setState(() {
                    selectedDropDownValue = value;
                  });
                },
                hint:Text("Select item")
            ),
          )

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 2021-10-24
    • 2020-06-07
    • 2021-07-30
    • 2020-12-16
    • 2021-03-21
    • 2022-01-16
    • 2013-08-15
    • 2021-09-17
    相关资源
    最近更新 更多