A clean and simple way to keep constants in Flutter is to make an own Dart library in the project for the constants.
For example, we have a project structure like this.
constats.dart
const String BUTTON_LABEL = 'Submit';
The const keyword is used to represent a compile-time constant. Variables declared with const keyword are implicitly final. Link
You can then use import statement to access to the constants:
import 'package:<project_name>/assets/constants.dart' as constants;
...
ElevatedButton(
child: const Text(constants.BUTTON_LABEL),
)
...
Top comments (2)
Hi, great article, but your constant violates [constant_identifier_names]. Dart constants should be lowerCamelCase, not UPPERCASE_WITH_UNDERSCORES. This avoids name changes when constants become final non-const variables. Also, enum values are const and lowercase. So, your example should be:
// constants.dart
const String buttonLabel = 'Submit';
… No offence, just a friendly correction. 😊
Nice to know 👏👏