What is the optimal way to catch errors inside the map function?

Viewed 194

I'm trying to catch errors inside a map function that should still continue iterating through the iterable.

So for example having this code:

const numbers = <String>['1', 'two', '3', '4', '5'];

final stringNum = numbers.map<int>((String num) {
  return int.parse(num);
}).toList();

will throw an Uncaught Error: FormatException: two.

I currently have these two solutions but is there a better way to solve this than using a for loop or a .whereType() function?

Using the .map Function with .whereType:

const numbers = <String>['1', 'two', '3', '4', '5'];

final stringToNum = numbers
  .map<int?>((String num) {
    try {
      return int.parse(num);
    } catch (e) {
      return null;
    }
  })
  .whereType<int>()
  .toList();

Using a plain for loop:

const numbers = <String>['1', 'two', '3', '4', '5'];

final forLoopNum = <int>[];
for (final num in numbers) {
  try {
    forLoopNum.add(int.parse(num));
  } catch (e) {
    continue;
  }
}
0 Answers
Related