Home > Software engineering >  What's the better way to expose constant string value in a class that can be used in Switch cas
What's the better way to expose constant string value in a class that can be used in Switch cas

Time:09-17

So this is the code, which won't work due to "Case expressions must be constant"

void main() {
  final id = 'someIdA';

  switch (id) {
    case ConstantsClass.a.id:
      // do something
      break;
    case ConstantsClass.b.id:
      // do something
      break;
  }
}

// exposing all the constants but grouping the constants in class by class fashion
class ConstantsClass {
  static _A get a => _A();
  static _B get b => _B();
}

// wrapping all the constants related to A
class _A {
  final id = 'someIdA';
}

// wrapping all the constants related to B
class _B {
  final id = 'someIdB';
}

And I have read posts about this "Case expressions must be constant" issue: 1 2

But I don't seem to find an answer from those posts.

And I also try to find another way to do use a class that contains only constant fields: What's the best practice to keep all the constants in Flutter? [closed] which also gives me not much hope...

And I think there's no way for me to use class with constant fields like ConstantsClass in the code here, the best I can get is to put all the constant values in one class, which I think will be very messy...

so is there a better way?

edit1:

I have a lot of String literal values that I want to manage using class, like in the case that's discussed in Effective Dart

So I can't use enum, unless I need to convert every string literal to enum, which I'm not sure if it's possible...

Thanks!

CodePudding user response:

Ok, this is how I keep track of String literals, so that I don't have to worry about mis-spelling them, and it's also really quick and easy to access them without having to type the whole name:

//Keep these in a file called constants.dart
//and let all begin with a k:
const String kIdA = 'someIdA';
const String kIdB = 'someIdB';


import 'constants.dart';

void main() {
  final id = 'someIdA';

  switch (id) {
    case kIdA:  //Here, when you use your constants, you just type kia, 
    // and the IDE will fill in the constant name.
    
    // do something
      break;
    case kIdB:
    // do something
      break;
  }
}

If you still insist on a version using a class, I think this should work better:

void main() {
  final id = 'someIdA';

  switch (id) {
    case ConstantsClass.idA:
    // do something
      break;
    case ConstantsClass.idB:
    // do something
      break;
  }
}

class ConstantsClass {
  static const idA = 'someIdA';
  static const idB = 'someIdB';
  static const idC = 'someIdC';
  static const idD = 'someIdD';
}
  •  Tags:  
  • dart
  • Related