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

963

Solution 1

C# is way too long ago, but it looks like Synchronous generators

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()

Solution 2

The equivalent in dart is with Stream and StreamController for async. And Iterable for sync. You can create them manually or using custom function with async* or sync* keywords

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

Solution 3

Dart has a simpler syntax to achieve what you want:

List<DropdownMenuItem<String>> _buildGitIgnoreTemplateItems() {
  return _gitIgnoreTemplateNames
      .map((g) => DropdownMenuItem(
            child: Text(g),
            value: g,
          ))
      .toList();
}
Share:
963
Anderson Oki
Author by

Anderson Oki

Updated on December 05, 2022

Comments

  • Anderson Oki
    Anderson Oki 3 minutes

    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:

    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#

  • Anderson Oki
    Anderson Oki over 4 years
    Worked like a charm. I can convert to a list using _buildGitIgnoreTemplateItems().toList(). Thank you @Günter
  • Günter Zöchbauer
    Günter Zöchbauer over 4 years
    Not sure though what the purpose is that you want to do it this way. Looks like what you want might be just _gitIgnoreTemplateNames.map((templateName) => DropdownMenuItem(child Text(templateName), value: templateName)).toList()
  • Anderson Oki
    Anderson Oki over 4 years
    The map method is what i was looking for. Thank you