7

I want to replace an URL String in Dart with another String. Example:

if (url == "http://www.example.com/1") {
home = "example";
} else if (url == "http://www.example.com/2") {
home = "another example";
}

Isn't there a better way with less code and maybe faster? I'd have to do this over 60 times..

Jona
  • 315
  • 1
  • 3
  • 9

5 Answers5

7

If you want less code, you can do somtehing like this :

homes = {
  "http://www.example.com/1": "example",
  "http://www.example.com/2": "another example",
  "http://www.example.com/3": "yet another one",
};
home = homes[url];
Muldec
  • 4,641
  • 1
  • 25
  • 44
5

I like Muldec's answer as I personally find switch statements to be a bit awkward to read. I also like the option of having a default so you could 'kind of' redefine the switch statement. The additional benefit is that you can use it inline as an expression and it is still typesafe...like this.

case2(myInputValue,
  {
    "http://www.example.com/1": "example",
    "http://www.example.com/2": "another example",
    "http://www.example.com/3": "yet another one",
  }, "www.google");

The case2 code could be

TValue case2<TOptionType, TValue>(
  TOptionType selectedOption,
  Map<TOptionType, TValue> branches, [
  TValue defaultValue = null,
]) {
  if (!branches.containsKey(selectedOption)) {
    return defaultValue;
  }

  return branches[selectedOption];
}
atreeon
  • 21,799
  • 13
  • 85
  • 104
1

You can use a switch statement.

switch(variable_expression) { 
   case constant_expr1: { 
      // statements; 
   } 
   break; 

   case constant_expr2: { 
      //statements; 
   } 
   break; 

   default: { 
      //statements;  
   }
   break; 
} 

References

Tinus Jackson
  • 3,397
  • 2
  • 25
  • 58
0

Mapp

              var mapper = {
                  'discountCode1': 0.5,
                  'discountCode2': 0.7,
                  'discountCode3': 0.8,
                };

Function

             double getDiscount(double price, String discountCode) {
                  if (mapper.containsKey(discountCode)) {
                    return mapper[discountCode]! * price;
                  } else {
                    return price;
                  }
                }
Paras Arora
  • 605
  • 6
  • 12
-2

Just store the value "http://www.example.com" in a string variable and concatinate everytime. Refer below code

String originalUrl = 'https://www.example.com';
if (url == originalUrl + '/1') {

}