Home > front end >  Access properties of a flutter class through the content of a variable
Access properties of a flutter class through the content of a variable

Time:05-11

I'm in Flutter (Dart), I want to access to a property of a class, but the property that I have to access is defined by the content of another variable.

Example: class

   class Fruit{
     String get apple {return 'The apples are red';}
     String get orange {return 'The orange are orange';}
   }

And I have a variable String variableName = 'apple'

I want to do

Fruit f = Fruit();
f.(variableName)

I don't know if is possible... Thanks in advance

Edited

Perhaps the example was very bad. I'm working with flutter_intl and the vscode extension, it automatically generates a class, AppLocations in my case like this:


class AppLocalizations {
  AppLocalizations();
...

  /// `Server failure`
  String get failure_server_failure {
    return Intl.message(
      'Server failure',
      name: 'failure_server_failure',
      desc: '',
      args: [],
    );
  }

  /// `Email already in use`
  String get failure_email_already_in_use {
    return Intl.message(
      'Email already in use',
      name: 'failure_email_already_in_use',
      desc: '',
      args: [],
    );
  }
...
}

I have the translations in the ARB files in JSON, but I wanted to show an error message in the corresponding language.

{
  "failure_server_failure": "Server failure",
  "failure_email_already_in_use": "Email already in use"
}

And I want to do this Text( AppLocations.of(context).*here* ) And in here put the failure code.

CodePudding user response:

You can define the variableName in the fruit class as static ...

Static String variableName ='apple';

CodePudding user response:

What if you define the class to accept a String. This will keep it generic enough to create multiple factory constructors

void main() {
  late Fruit a;
  late Fruit o;

  a = Fruit.apple();
  o = Fruit.orange();
  
  print(a);
  print(o);
}

class Fruit {
  final String text;

  const Fruit({required this.text});

  factory Fruit.empty() => Fruit(text: '');

  factory Fruit.apple() => Fruit(text: 'The apples are red');

  factory Fruit.orange() => Fruit(text: 'The oranges are orange');

  @override
  String toString() => 'The text is:  $text';
}
  • Related