Alexis Mejía
Alexis Mejía

Reputation: 104

How to create an advance condition if some strings are different than null in flutter

I have a little problem that maybe you solved it. I have 3 Strings which can be null, I want to create a condition depending if the String Is null or not. In my code below I create and if condition for every case

(String1 != null)
(String1 != null && String2!=null)
(String1 != null && String2 != null && String3 !=null)
(String2!=null).... etc

I know that this is not the best way to do it, does anybody know how to optimice my current code?

My idea is create something like

if(original condition... if(String1 != null adds something like "&& String1 == customCond") and if (String2 != null adds "&& String 2 == customCond)

enter image description here

Upvotes: 0

Views: 449

Answers (2)

Salar Arabpour
Salar Arabpour

Reputation: 520

First of all, prefer copying code rather than screenshot. Then, if I wanna refactor this, fastest option would be extract these multiple conditions to a method, for example first if would be a method named 'hasProyectoCondition' . On the other hand, if you want to ease logic implementation you can use abstract class as a parent to all your conditions which are actually your concrete classes. For more information you can take a look at strategy design pattern at https://refactoring.guru

Upvotes: 0

Renato
Renato

Reputation: 13690

There's no escaping handling all cases...

But you can make the code a little bit prettier by delegating the checks to an external function and only handling cases you actually care about.

With 3 Strings, there are 2^3 = 8 cases to handle. But if you only care about cases where only one of them will be non-null, you can handle only 3 cases plus the "else" case.

I would create a function that takes functions for handling each interesting case like this:


// ugly, but you write this only once and hide it well
void handleStrings(
  String? s1,
  String? s2,
  String? s3,
  Function(String, Never?, Never?) f1,
  Function(Never?, String, Never?) f2,
  Function(Never?, Never?, String) f3,
  Function() otherwise,
) {
  if (s1 != null) {
    f1(s1, null, null);
  } else if (s2 != null) {
    f2(null, s2, null);
  } else if (s3 != null) {
    f3(null, null, s3);
  } else {
    otherwise();
  }
}

// example usage
void main() {
  handleStrings(
    "foo",
    null,
    null,
    // look, no if's anymore!!!
    (s1, _, __) => print("Got s1: $s1"),
    (_, s2, __) => print("Got s2: $s2"),
    (_, __, s3) => print("Got s3: $s3"),
    () => print("something else"),
  );
}

Upvotes: 1

Related Questions