C#在循环上的Dart / Flutter返回列表<string>上的收益率返回

时间:2018-07-16 09:48:42

标签: dart flutter

我有以下方法:

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#

3 个答案:

答案 0 :(得分:2)

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

/**
 * You are given startingAmount of Apples. Whenever you eat a certain number of
 * apples (newEvery), you get an additional apple.
 *
 * What is the maximum number of apples you can eat?
 *
 * For example, if startingAmount equals 3 and newEvery equals 2, you can eat 5 apples in total:
 * 
 * Eat 2. Get 1. Remaining 2.
 * Eat 2. Get 1. Remaining 1.
 * Eat 1.
 */

但是也许你只是想要

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

答案 1 :(得分:1)

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

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


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

答案 2 :(得分:1)

Dart具有更简单的语法来实现您想要的目标:

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