What\'s the best programming practice to
create a constant class in Flutter
to keep all the application constants for easy referenc
EDIT
Now that the flag --dart-define
has been added to the different command lines of Flutter, the following answer no-longer applies.
Instead just declare constants wherever you want, and potentially refer to other answers.
While there are no technical issues with static const
, architecturally you may want to do it differently.
Flutter tend to not have any global/static variables and use an InheritedWidget.
Which means you can write:
class MyConstants extends InheritedWidget {
static MyConstants of(BuildContext context) => context. dependOnInheritedWidgetOfExactType();
const MyConstants({Widget child, Key key}): super(key: key, child: child);
final String successMessage = 'Some message';
@override
bool updateShouldNotify(MyConstants oldWidget) => false;
}
Then inserted at the root of your app:
void main() {
runApp(
MyConstants(
child: MyApp(),
),
);
}
And used as such:
@override
Widget build(BuilContext context) {
return Text(MyConstants.of(context).successMessage);
}
This has a bit more code than the static const
, but offer many advantages:
But at the same time it: