Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic inside List.map

Tags:

dart

I want to include logic inside my list mapping. Example:

I can do something like this:

List projects = urls.map((url) => url.substring(0, 3)).toList();

But can I, somehow, do something like this:

List projects = urls.map((url) {
  if (url.indexOf("?") == -1) {
    url;
  } else {
    url.substring(0, url.indexOf("?"));
  }
}).toList();
like image 875
Dani Avatar asked Feb 21 '26 12:02

Dani


1 Answers

Of course you can. What is missing is a return statement.
With the short function format (=>) return is implicit and the result of the expression gets returned. If you use the function block format you have to explicitly return the value you want to have in the result. Without an explicit return null is returned.

List projects = urls.map((url) {
  if (url.indexOf("?") == -1) {
    return url;
  } else {
    return url.substring(0, url.indexOf("?"));
  }
}).toList();
like image 64
Günter Zöchbauer Avatar answered Feb 24 '26 14:02

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!