【问题标题】:Can I get multiple return from dropdownbutton?我可以从下拉按钮获得多个返回吗?
【发布时间】:2021-12-01 15:09:06
【问题描述】:

我今天尝试将 json 设置为下拉按钮。

但我想从中获取 2 个值(ID 和 Name)。

这是我的 json

[{"StudentID":"3","StudentName":"Amy"},{"StudentID":"4","StudentName":"Derek"}]

这是我的下拉按钮代码。

Row(
          children: <Widget>[Container(
              padding: EdgeInsets.only(left:5),
              child: new DropdownButton(
                value: _StudentSelection,
                items: StudentData.map((product) {
                  return new DropdownMenuItem(
                      value: product["StudentID"].toString(),
                      child: new Text(product["StudentName"]!)
                  )
                }).toList(),
                onChanged: (String? newValue) {
                  setState(() {
                    _StudentSelection = newValue!;
                  });
                },
                hint: Text('StudentID'),
              )
          ),
          ],
        ),

在这种情况下,_StudentSelection 已经由 Amy 初始化,StudentData 是解码 json 的结果。

感谢您看到这个问题:)

【问题讨论】:

  • 可以添加错误信息吗?
  • @SalihCan 没有错误。但在这种情况下,我只能从中获得一个值。
  • 你想在这个下拉列表中也显示 id 和 name 吗?
  • 参考我的回答here希望对你有帮助
  • @RavindraS.Patil 是的。这对我帮助很大。谢谢!

标签: flutter dart


【解决方案1】:

使_StudentSelection 变量的类型与product 变量的类型相同,然后将product 用作value:,而不仅仅是ID。

Row(
          children: <Widget>[Container(
              padding: EdgeInsets.only(left:5),
              child: new DropdownButton(
                value: _StudentSelection, // change this variables type to the type of your product variable
                items: StudentData.map((product) {
                  return new DropdownMenuItem(
                      value: product, // use the whole product as value
                      child: new Text(product["StudentName"]!)
                  )
                }).toList(),
                onChanged: (TYPE_OF_PRODUCT_HERE? newValue) {
                  setState(() {
                    _StudentSelection = newValue!;
                  });
                },
                hint: Text('StudentID'),
              )
          ),
          ],
        ),

【讨论】:

  • 这个时候如何初始化变量呢?字符串很简单,但我现在什么都没想。
  • 你想把它初始化成什么?我什至不知道它是什么类型。
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多