31.58 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

const int windowWidth = 1234;

Discouraged

const int WINDOW_WIDTH = 12345;

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:

var monthsInYear = 12;
const daysInYear = 365;

A final variable (which is also a constant) is assigned its value at runtime.

final today = DateTime.now();

Where to Define Constants

Constants that are required in multiple other dart files belong in lib/constants/app.dart. These will generally be the app title/name of the app, locations shared across the app, like assets, and could also include layout type constants like padding. A specific collection of other constants used for styling the app might be, for example, in lib/constants/colours.dart or lib/constants/fonts.dart, for example.

Constants that are specific to a page or widget, and not shared across other files should go into the specific page or widget source file. If they are specific to a subset of files, then they could, for example, go into lib/constants/surveys.dart for a collection of pages relating to surveys.



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