微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。