Home > Software design >  Advanced switch case in flutter
Advanced switch case in flutter

Time:09-01

I can write switch statement in iOS/Swift like this,

enum Test {
    case none
    case first(Int)
    case second(String)
    case third(Bool)
    
    var value:String {
        switch self {
        case .none:
            return "None"
        case .first(let int):
            return "First case with Integer value - \(int)"
        case .second(let string):
            return "Second case with String value - \(string)"
        case .third(let bool):
            return "Third case with Boolean value - \(bool)"
        }
    }
}

class Testing {
    
    func execute() {
        print(Test.none.value)
        print(Test.first(10).value)
        print(Test.second("Vatsal").value)
        print(Test.third(true).value)
    }
    
}

But how to write an advanced switch statement in flutter?

Kindly, share your knowledge.

CodePudding user response:

I think Dart 2.17 Added the enhanced enums, So thats the closest thing in dart to what u r asking here. You can find more details at this thread How do I add Methods or Values to Enums in Dart?

CodePudding user response:

To get the same behaviour I would implement it like this:

void main() {
  print(Test.none().value);
  print(Test.first(10).value);
  print(Test.second("Vatsal").value);
  print(Test.third(true).value);
}

class Test {
  dynamic _value;

  Test._([this._value]);

  factory Test.none() => Test._();
  factory Test.first(int i) => Test._(i);
  factory Test.second(String s) => Test._(s);
  factory Test.third(bool b) => Test._(b);

  String get value {
      switch (_value.runtimeType) {
        case Null: return "None";
        case int: return "First case with Integer value - $_value";
        case String: return "Second case with String value - $_value";
        case bool: return "Third case with Boolean value - $_value";
        default: throw Exception();
      }
  }
}
  • Related