簡體   English   中英

包含項的映射中的return語句:Flutter DropdownButton中的原因和作用方式

[英]Return statement within a map with items: within Flutter DropdownButton, Why and How it works

我是Flutter和Dart的新手。 我正在遵循免費教程,但是我對在map中的dropdownButton中的item中如何有一個return語句感到困惑。 這是如何運作的? 我正在尋找有關return語句為何存在以及將其值發送到何處的說明。

我試圖查找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,
          ),

命名可能會使新手感到困惑,但讓我為您解釋一下您發布的代碼:

所以DropdownButton構造期望列表DropdownMenuItem作為參數,但在你的情況你沒有列表DropdownMenuItem你有一個列表String 您需要的是一種將String轉換為DropdownMenuItem ,最簡單的方法是對字符串進行for ,為您擁有的每個String創建一個新的DropdownMenuItem ,將其添加到列表中,然后將其發送到DropdownButton 就像是:

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轉換為一個Iterable而不是一個List(您不能將IterableList ),幸運的是Iterable具有另一種稱為toList()方法,該方法會將其轉換為List

現在,在您的情況下,必須轉換的列表是_currencies ,所應用的功能是:

 (String dropDownStringItem) {

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

dropDownStringItem將采用_currencies中每個元素的_currencies return DropdownMenuItem ...將返回轉換后的對象

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM