1

我是 Flutter 和 Dart 的新手。我正在关注一个免费教程,但我很困惑如何在项目中的地图中有返回语句:在 DropdownButton 中。这是如何运作的?我正在寻找关于为什么 return 语句存在以及它在哪里发送其值的说明。

我试图查找返回语句是如何在地图中的,但我可能会误认为如何提出这个问题。代码按给定的方式工作,但我不确定它是如何工作的。是否有此代码的逐步简化形式,可能会导致更多的理解。就像现在“它在我头上”。

          DropdownButton<String>(

            items: _currencies.map(
                    (String dropDownStringItem) {

                   // interested in this return statement 
                  return DropdownMenuItem<String>(
                    value: dropDownStringItem,
                    child: Text(dropDownStringItem),
                  );
                }
            ).toList(),  //convert to List


            onChanged: (String newValueSelected) {
              _onDropDownItemSelected(newValueSelected);
            },

            value: _currentItemSelected,
          ),
4

1 回答 1

0

命名可能会让新手感到困惑,但让我为您解释一下您发布的代码:

所以DropdownButton构造函数期望一个DropdownMenuItem作为参数的列表,但在你的情况下,你没有一个列表,DropdownMenuItem你有一个String. 您需要一种将 String 转换为 a的方法DropdownMenuItem,最简单的方法是对字符串执行 a ,为您拥有的每个for创建一个新的,将其添加到列表中,然后将其发送到. 就像是:DropdownMenuItemStringDropdownButton

List<DropdownMenuItem> newGenerated = [];
_currencies.forEach((value) {
    DropdownMenuItem newItem = DropdownMenuItem<String>(
                                  value: dropDownStringItem,
                                  child: Text(dropDownStringItem),
                                 );
    newGenerated.add(newItem)
}
 DropdownButton<String>(
        items: newGenerated,  //convert to List
        onChanged: (String newValueSelected) {
          _onDropDownItemSelected(newValueSelected);
        },
        value: _currentItemSelected,
      ),

上面的代码和你的代码做同样的事情,但在我看来不是那么好。

您正在使用的函数map用于将对象列表转换Iterable为其他元素,对列表中要转换的每个元素应用一个函数。

需要记住的一件事是,map 转换为 anIterable而不是 List(您不能转换IterableList),幸运的是,Iterable还有另一种方法toList()可以将其转换为List.

现在在您的情况下,必须转换的列表_currencies是应用的函数:

 (String dropDownStringItem) {

                   // interested in this return statement 
                  return DropdownMenuItem<String>(
                    value: dropDownStringItem,
                    child: Text(dropDownStringItem),
                  );

dropDownStringItem_currencies. 将return DropdownMenuItem ...返回转换后的对象

希望这会有所帮助。

于 2019-04-23T20:08:27.977 回答