0

Is it possible to create slightly varying instances of a class based on two parameters A and B so that

  1. If A and B are present --> create instance variation AB
  2. If A and not B are present --> create instance variation A
  3. If not A and B are present --> create instance variation B
  4. If neither A nor B are present --> do not allow instance creation

Is this kind of parameter "or" even possible? Should I create guards or use switch case and branch to different subclasses? Or is there a way to use factories? I tried using factories before, but because the returning instances should have the same base class I am having problem creating this common base for them.

The class I am trying to create could be something like this:

class WeirdProblem extends StatelessWidget {
  WeirdProblem({
    Key? key,
    this.A,
    this.B,
    this.someParam = someValue,
    required anotherParam,
  }) : super(key: key);

  final SomeType? A;
  final AnotherType? B;
  final Type someParam;
  final Type anotherParam;
  
  /// How to create the instances so that the
  /// parameters A and B are logically or'd?
}

class AB extends StatelessWidget {
  AB({
    required A,
    required B,
  })
  ...
}

class A extends StatelessWidget {
  A({
    required A,
  })
  ...
}

class B extends StatelessWidget {
  B({
    required B,
  })
  ...
}

/// class without A and B doesn't exist

zaplec
  • 1,681
  • 4
  • 23
  • 51

1 Answers1

0

I don't know if I understood your question well, but this is what I came up with:

class WeirdProblem {
  WeirdProblem({
    Key? key,
    this.a,
    this.b,
  }) {
    if (a != null) {
      if (b != null) {
        type = AB(a: a, b: b);
      } else {
        type = a;
      }
    } else if (b != null) {
      type = b;
    }
  }

  A? a;
  B? b;
  dynamic type;
}

class AB {
  AB({
    required this.a,
    required this.b,
  });

  A? a;
  B? b;
}

class A {
  A({
    required this.a,
  });
  String a;
}

class B {
  B({
    required this.b,
  });

  String b;
}

So now if you create different instances, the type will be of that insance.

final a = WeirdProblem(a: A(a: "a"));
final b = WeirdProblem(b: B(b: "b"));
final ab = WeirdProblem(a: A(a: "a"), b: B(b: "b"));

print(a.type); // Instance of 'A'
print(b.type); // Instance of 'B'
print(ab.type); // Instance of 'AB'
Ante Bule
  • 1,834
  • 1
  • 2
  • 8