简体   繁体   English

C#飞镖/颤振返回列表的收益率列表 <String> 循环中

[英]C# Yield Return on Dart / Flutter Return List<String> in Loop

I have the following method: 我有以下方法:

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

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

    return _dropDownMenuItems;
}

What i am trying to achived is remove the variable _dropDownMenuItems something like: 我想要实现的是删除变量_dropDownMenuItems ,例如:

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

You can see similar implementation in other languages like: C# 您可以看到其他语言的类似实现,例如: C#

C# is way too long ago, but it looks like Synchronous generators C#太早了,但是看起来像同步生成器

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

but perhaps you just want 但是也许你只是想要

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

The equivalent in dart is with Stream and StreamController for async. dart中的等效项是StreamStreamController用于异步。 And Iterable for sync. 并且可Iterable进行同步。 You can create them manually or using custom function with async* or sync* keywords 您可以手动创建它们,也可以使用带有async*sync*关键字的自定义功能

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


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

Dart has a simpler syntax to achieve what you want: Dart具有更简单的语法来实现您想要的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM