Home > Back-end >  How do I get dynamic class return back from the enum class cases in dart?
How do I get dynamic class return back from the enum class cases in dart?

Time:11-26

I was working on iOS, and now I have to deal with flutter.

The case is when I was using swift, I'm able to access the rule variable with different class type based on different enum cases.

example code as below:

enum SensorTypeRule{
    case Lamp(rule:LampRule)
    case Counter(rule:CounterRule)
}
struct LampRule{
    let ruleTriggerColor: LampColor
    let ruleSustainedMilliseconds: UInt32
}
struct CounterRule{
    let ruleLimit: UInt32
}

   

and can be access like below:

let sensorTypeRule:SensorTypeRule = someSensorTypeRuleInstance
switch sensorTypeRule{
                    case .Lamp(let rule):
                        print("\(rule. ruleSustainedMilliseconds)")
                    case .Counter(let rule):
                        print("\(rule.ruleLimit)")
}

Is there an equivalent approach in dart?

CodePudding user response:

Dart does not have the concept of sealed classes, however you can do this way:

// Create an abstract class representing an enum
// This enum can be instantiated in two ways: either
// calling SensorTypeRule.lamp or SensorTypeRule.counter
abstract class SensorTypeRule {
  const factory SensorTypeRule.lamp(LampRule rule) = Lamp._;
  const factory SensorTypeRule.counter(CounterRule rule) = Counter._;
  
  const SensorTypeRule();
}

// Create the rules inside each respective class
// Using _ as constructor name disallows the user
// to instantiate it directly          -> Lamp(...)
// Instead, it must use the base class -> SensorTypeRule.lamp(...)

class Lamp extends SensorTypeRule {
  final LampRule rule;

  const Lamp._(this.rule);
}

class Counter extends SensorTypeRule {
  final CounterRule rule;

  const Counter._(this.rule);
}

// Define the rules 

class LampRule {
  final LampColor ruleTriggerColor;
  final int ruleSustainedMilliseconds;

  const LampRule({
    required this.ruleTriggerColor,
    required this.ruleSustainedMilliseconds,
  });
}

class CounterRule {
  final int ruleLimit;

  const CounterRule({
    required this.ruleLimit,
  });
}

When accessing it, you can do this way:

final SensorTypeRule sensorTypeRule =
      SensorTypeRule.counter(CounterRule(ruleLimit: 10));

if (sensorTypeRule is Lamp) {
  print(sensorTypeRule.rule.ruleSustainedMilliseconds);
} else if (sensorTypeRule is Counter) {
  print(sensorTypeRule.rule.ruleLimit);
}
  •  Tags:  
  • dart
  • Related