1

Background

While following London App Brewery's Bitcoin Ticker project, and I got stuck trying to create DropdownMenuItems via a for-in loop. The warning that the Dart Analysis gave me was Undefined name 'currency'. Here's the code that produced the error:

Problematic Code

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

Question

What does Undefined name 'currency' mean in Dart? Does that really mean it's an undefined variable named 'currency'?

chemturion
  • 283
  • 2
  • 16

1 Answers1

0

Android Studio IDE Hint

My IDE gave me three hints, and the top one Create local variable 'currency' seemed to be the correct solution. However, it creates the variable outside of the for-in loop. The problem was that currency in the for-in loop wasn't defined.

Create local variable 'currency'

Create local variable 'currency'

Local variable 'currency' defined outside for-in loop

Technically, this way of defining currency is correct, but is verbose and requires an extra line of code. Local variable 'currency' defined

Solution

I placed the variable type inside the for-in loop like they show in the Dart docs. I also changed the generic var to the more specific String type for each item in the list.

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