【问题标题】:C# Yield Return on Dart / Flutter Return List<String> in Loop循环中 Dart / Flutter Return List<String> 上的 C# Yield Return
【发布时间】:2018-07-16 09:48:41
【问题描述】:

我有以下方法:

List<DropdownMenuItem<String>> _buildGitIgnoreTemplateItems() {
    var _dropDownMenuItems = List<DropdownMenuItem<String>>();

    _gitIgnoreTemplateNames.forEach((templateName) {
        _dropDownMenuItems.add(DropdownMenuItem(
            child: Text(templateName),
            value: templateName,
        ));
    });

    return _dropDownMenuItems;
}

我想要实现的是删除变量_dropDownMenuItems 类似:

List<DropdownMenuItem<String>> _buildGitIgnoreTemplateItems() {
    _gitIgnoreTemplateNames.forEach((templateName) {
        **yield return** DropdownMenuItem(
            child: Text(templateName),
            value: templateName,
        );
    });
}

您可以在其他语言中看到类似的实现,例如:C#

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    dart 中的等价物是 StreamStreamController 用于异步。和Iterable 同步。您可以手动创建它们,也可以使用带有 async*sync* 关键字的自定义函数

    Iterable<String> foo() sync* {
      yield "Hello";
    }
    
    
    Stream<String> foo() async* {
      yield "Hello";
    }
    

    【讨论】:

      【解决方案2】:

      C# 太早了,但它看起来像Synchronous generators

      Iterable<DropdownMenuItem<String>> _buildGitIgnoreTemplateItems() sync* {
          for(var templateName in _gitIgnoreTemplateNames) {
              yield DropdownMenuItem(
                  child: Text(templateName),
                  value: templateName,
              );
          }
      }
      

      但也许你只是想要

      _gitIgnoreTemplateNames.map((templateName) => 
          DropdownMenuItem(
            child Text(templateName), 
            value: templateName)
          ).toList()
      

      【讨论】:

      • 工作就像一个魅力。我可以使用_buildGitIgnoreTemplateItems().toList() 转换为列表。谢谢@Günter
      • 不确定您这样做的目的是什么。看起来你想要的可能只是_gitIgnoreTemplateNames.map((templateName) =&gt; DropdownMenuItem(child Text(templateName), value: templateName)).toList()
      • map 方法正是我想要的。谢谢
      【解决方案3】:

      Dart 有更简单的语法来实现你想要的:

      List<DropdownMenuItem<String>> _buildGitIgnoreTemplateItems() {
        return _gitIgnoreTemplateNames
            .map((g) => DropdownMenuItem(
                  child: Text(g),
                  value: g,
                ))
            .toList();
      }
      

      【讨论】:

        猜你喜欢
        • 2020-02-18
        • 2021-11-18
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        • 2012-12-07
        • 2021-09-12
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多