I have a class for my app that controls some properties. I am trying to achieve something similar to this (code does not work):
class App {
static final AppColors colors = AppColors;
static final AppVariables variables = AppVariables;
}
Quick example of what I am trying to achieve:
App.colors.accent OR App.variables.storage
AppColors
and AppVariables
are abstract class with only static variables. The code above does not work and the normal way is to just get an instance of each class with:
static final AppColors colors = AppColors();
but the problem is then the static variables and methods in my AppColors
class wont work, obviously.
Question is: How do I point to a class with a variable (without instantiating it)?
CodePudding user response:
Just remove static from all variables from AppColors
and Appvariables
classes. Since you initialize those classes in a static variable, you can call their non-static variables at once. Let me show you an example.
class App {
static final AppColors colors = AppColors();
}
class AppColors{
final int color1 = 3;
}
You can call like this.
void main() {
print("VALUE ${App.colors.color1}");
}
That's it.
CodePudding user response:
First off: you can't. A static member belongs to the class itself, not an object of the class. Thus, colors
will never have an accent
and variables
will never have a storage
(with your current design). You can still do AppColors.accent
or AppVariables.storage
, or make the fields of AppColors
and AppVariables
non-static so that you can do colors.accent
and variables.storage
.
Second off: this looks like you are trying to do some sort of state management with this approach. Whenever you change one of those values, the application will not react to that state change. I'd recommend taking a look at get_it
or riverpod
to correctly handle state management.
Edit: you could also use the singleton pattern to do this, but I would highly recommend taking a look at riverpod or get_it first.