flutterdartconstants

Dart / Flutter nested classes static access


I'm trying to use a version of nested classes to make a tree of constant strings throughout my app in Flutter. I'd like them to be nested in order to find const strings quickly as the app grows, but still have the additional 'speed' of using the const keyword for Text() widgets.

However, I'm having a hard time trying to use them in const Text() widgets.

Here's a sample:

class Strings {
  static const String ok = 'OK';
  static TechnicianStrings technicianStrings = TechnicianStrings();
}

class TechnicianStrings {
  TechnicianStrings();
  final String createTech = 'Create Technician';
  final String technician = 'Technician';
}

Throughout the app, I'd like to use these constant Strings as so:

const Text(Strings.ok),  // <-- this works
const Text(Strings.technicianStrings.technician), //<-- only works without 'const'
const Text(Strings.technicianStrings.createTech), //<-- only works without 'const'

However, I get an error of "Arguments of a constant creation must be constant expressions" when I use the const keyword for the text widgets.

I've tried to use varying "const and static" names for the members of TechnicianStrings, and I get errors such as "invalid Constant" for the text widget. I also defined TechnicianStrings as static const, and got an error of 'Constant variables must be initialized with a constant value' for the line:

static const TechnicianStrings technicianStrings = TechnicianStrings();

Is there a way to use such a nested class structure hand in hand with const Text() widgets?


Solution

  • You need a constant constructor in TechnicianStrings.

    class Strings {
      static const String ok = 'OK';
      static const TechnicianStrings technicianStrings = TechnicianStrings();
    }
    
    class TechnicianStrings {
      const TechnicianStrings(); // <---
      final String createTech = 'Create Technician';
      final String technician = 'Technician';
    }