如何在 Flutter for-in 循环中解析未定义的名称“货币”?

问题描述

背景

在关注 London App Brewery 的 Bitcoin Ticker 项目时,我在尝试通过 for-in 循环创建 DropdownMenuItem 时遇到了困难。 Dart 分析给我的警告是 Undefined name 'currency'。这是产生错误代码

有问题的代码

List<DropdownMenuItem<String>> buildCurrencyDropdownMenuItems() {
  List<DropdownMenuItem<String>> items = [];
  for (currency in currenciesList) {
    items.add(DropdownMenuItem(child: Text(currency),value: currency));
  }
  return items;
}

问题

Undefined name 'currency' 在 Dart 中是什么意思?这是否真的意味着它是一个名为“货币”的未定义变量

解决方法

Android Studio IDE 提示

我的 IDE 给了我三个提示,最上面的一个创建局部变量 'currency' 似乎是正确的解决方案。但是,它会在 for-in 循环之外创建变量。 问题在于 for-in 循环中的 currency 未定义

创建局部变量“货币”

Create local variable 'currency'

在 for-in 循环外定义的局部变量“货币”

从技术上讲,这种定义 currency 的方式是正确的,但很冗长,需要额外的一行代码。 Local variable 'currency' defined

解决方案

我将变量类型放在 for-in 循环 like they show in the Dart docs 中。我还为列表中的每个项目将通用 var 更改为更具体的 String 类型。

List<DropdownMenuItem<String>> buildCurrencyDropdownMenuItems() {
  List<DropdownMenuItem<String>> items = [];
  for (String currency in currenciesList) {
    items.add(DropdownMenuItem(child: Text(currency),value: currency));
  }
  return items;
}