31.72 Flutter Style Constants
20230813
How to Name a Constant
Historically I have preferred SCREAMING_CAPS for my constants. This is a traditional approach but is effective in clearly identifying what is a CONSTANT. However, in dart the recommendation is to use lower camel case. Within the code it is not so clear what is a constant and what is a variable, but there is often no specific need to know the difference. This is perhaps okay as the compiler picks up any errant assignments to a constant. For flutter I recommend this style too.
Preferred
Discouraged
Then, within my code when using windowWidth
it is not clear whether that
is a variable or a constant or a instance, etc. But that is probably okay.
Why Define a Constant
A value that is never to change. Also it tells the compiler this fact and the compiler can take advantage of this in optimising the code and in reloading the code.
Example of an implicit variable and a constant:
A final
variable (which is also a constant) is assigned its value
at runtime.
Where to Define Constants
Constants that are required in multiple dart files belong within
lib/constants/
and perhaps to start with in
lib/constants/app.dart
. These constants might be the title/name of
the app, locations shared across the app, like assets, and could also
include layout type constants like padding and spacing. As the app and
number of constants grow, then specific collections of constants might
move to their own files within lib/constants/
. For example,
constants used for styling the app might be in
lib/constants/colours.dart
or lib/constants/fonts.dart
. Constants
that are used for spacing the widgets throughout the app might go into
lib/constants/spacing.dart
.
Constants that are specific to a page or widget or some other specific dart file, and not shared across other files, should go into the specific dart source file.
Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0