flutter - 我可以在 Dart 中传递枚举类型作为参数吗?

标签 flutter dart

我想要一个方法,它将枚举类型的参数作为参数,然后对其进行操作以获取枚举类型的所有可能值,并对每个值进行一些处理。

我希望有这样的事情:

Widget foo (EnumType enumType) {
    for(var value in enumType.values) {
        print(value.name);
    }
}

我一直在寻找解决方案,但我能找到的唯一解决方案是通过将值列表作为参数传递来解决,但这并不能解决我的问题,因为即使使用对象列表,我也无法解决知道它们是枚举值,因此如果我尝试对它们执行 .name 操作,dart 会抛出错误 Error: The getter 'name' isn't Defined for the class 'Object'。 也许我唯一的问题是我不知道如何将变量指定为 EnumType,但我无法为此找到正确的类型。

最佳答案

EnumType.values 相当于 EnumType 上自动生成的 static 方法,因此不是任何对象接口(interface)的一部分。因此,您将无法直接动态调用 .values

I've looked for solutions but the only ones I can find are addressed by passing a list of the values as a [parameter], however this doesn't solve my problem as, even with the list of objects, I can't know that they are enum values so if I try do the .name operation on them, dart throws an error

您可以使用通用函数,将其类型参数限制为Enum:

enum Direction {
  north,
  east,
  south,
  west,
}

List<String> getNames<T extends Enum>(List<T> enumValues) =>
    [for (var e in enumValues) e.name];

void main() {
  print(getNames(Direction.values)); // Prints: [north, east, south, west]
}

关于flutter - 我可以在 Dart 中传递枚举类型作为参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71841968/

相关文章:

flutter - 返回并显示 snackbar

Flutter:如何合并两个 StreamBuilder 并在卡片中显示输出

dart - Flutter - ListView更新后拖动动画未返回开始

flutter - 使用 Flutter 获取设备货币

flutter - 如何在列中对齐小部件?

Flutter 和 Angular Dart 都共享组件模式,但是这两个框架之间的一个根本区别是什么?

firebase - flutter 地实现搜索栏

android - Flutter:如何在两个单独的android应用之间安全地共享数据?

dart - 如何在 Flutter 中使用 BottomNavigationBar 构建页面