What's the best practice to keep all the constants in Flutter?

72,216

Solution 1

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<MyConstants>();

  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:

  • Works with hot-reload
  • Easily testable and mockable
  • Can be replaced with something more dynamic than constants without rewriting the whole app.

But at the same time it:

  1. Doesn't consume much more memory (the inherited widget is typically created once)
  2. Is performant (Obtaining an InheritedWidget is O(1))

Solution 2

My preferred solution is to make my own Dart library.

Make a new dart file named constants.dart, and add the following code:

const String SUCCESS_MESSAGE=" You will be contacted by us very soon.";

Edit: 99% of the time you don't need to explicitly name your dart libraries with a statement like library library_name; at the top of your file, and you probably shouldn't (reference).
Even if you leave out this line your file will still be library! It will just be implicitly named.

Then add the following import statement to the top of any dart file which needs access to the constants:

import 'constants.dart' as Constants;

Note if constants.dart is in different directory then you will need to specify the path to constants.dart in your import statement.

EDIT: Use lowercase_with_underscores when specifying a library prefix.

In this example:

enter image description here

You could use a relative path:

import '../assets/constants.dart' as constants;

Or an absolute path from the lib directory:

import 'package:<your_app_name>/assets/constants.dart' as constants;

Now you can easily access your constants with this syntax:

String a = Constants.SUCCESS_MESSAGE;

Solution 3

Referring to https://dart.dev/guides/language/effective-dart/design

It's a good practice to group, constants and enum-like types in a class like below:

enter image description here

Auto import is straightforward in Android Studio, where you can type the class name Color, and Android Studio will be able to suggest auto import of Color class.

Solution 4

I've noticed a little confusion across the answers here, so I thought I would try to clear a few things up.

Dart/Flutter guidelines suggest not creating classes that only contain static members, namely because it isn't necessary. Some languages, such as Java or C# will not allow you to define functions, variables, or constants outside of a class, but Dart will. Therefore, you can simply create a file such as constants.dart that contains the constants that you want to define.

As noted by @Abhishek Jain, the library keyword is not required for this method to work. The library keyword is used for libraries that will be published for use in other projects, although it can be used along with part and part of to break a single library up across multiple files. However, if you need that, then your needs are probably beyond the scope of OP's question.

As pointed out by @ChinLoong, it is technically acceptable to create a class that groups related constants and enum-like types. It should be noted however that this demonstrates an exception to the guideline as it is not a hard rule. While this is possible, in Dart, it is frowned upon to define a class that is never instantiated. You'll notice that the Dart Color class that defines Color constants has a constructor which excepts an integer value, allowing instantiation for colors not defined by a constant.

In conclusion, the approach that best adheres to the Dart guidelines is to create a constants.dart file or a constants folder containing multiple files for different constants (strings.dart, styles.dart, etc.). Within the constants.dart file, define your constants at the top level.

// constants.dart
 
const String SUCCESS_MESSAGE=" You will be contacted by us very soon.";

...

Then, import the file wherever the constants need to be used and access directly via the constant's name.

Solution 5

That's completely up to you.
Using static has no disadvantages.
Actually const is required for fields in a class.

Share:
72,216

Related videos on Youtube

Manoj Perumarath
Author by

Manoj Perumarath

ചവറു പോലെ എഴുതുന്നത് എനിക്ക് ഇഷ്ടമല്ല ! Hey there, if you have found my answers helpful you can buy me a coffee! Currently, Senior Mobile Developer at Emvigo Technologies, Kaloor, Ernakulam, Kerala.

Updated on February 08, 2022

Comments

  • Manoj Perumarath
    Manoj Perumarath over 2 years

    What's the best programming practice to

    create a constant class in Flutter

    to keep all the application constants for easy reference. I know that there is const keyword in Dart for creating constant fields, but is it okay to use static along with const, or will it create memory issues during run-time.

    class Constants {
    static const String SUCCESS_MESSAGE=" You will be contacted by us very soon.";
    }
    
    • Hyung Tae Carapeto Figur
      Hyung Tae Carapeto Figur over 3 years
      Just a little comment. In Dart, unlike most of the other languages, it has a nomenclature convention of lowerCamelCase for constants.
  • Wecherowski
    Wecherowski over 4 years
    "Flutter tend to not have any global/static variables and use an InheritedWidget". Where is that said though? I come from traditional Java Development and this feels incredibly hacky ...
  • Rémi Rousselet
    Rémi Rousselet over 4 years
    @Wecherowski it's implicit by what Flutter exposes. There are very, very few static variables when opposed to InheritedWidgets. You can use whatever you like though.
  • tvw
    tvw over 4 years
    "Flutter tend to not have any global/static variables and use an InheritedWidget". Constants are per definition no variables. Therefore I do not understand, what you try to solve with an InheritedWidget.
  • Rémi Rousselet
    Rémi Rousselet over 4 years
    @tvw "constants" also includes things like "isInDebugMode" or the current platform. They are constants for a build, but may change between builds. Using InheritedWidgets allows an easier workflow when dealing with these, such as mocking their value, or changing it live in dev mode.
  • Magnus Johansson
    Magnus Johansson over 4 years
    This seems to be not so suitable for Blocs, which I use a lot. With this approach, I have to share/pass the context(s) to my Blocs, no?
  • nt4f04und
    nt4f04und about 4 years
    My approach is very similar: I just have a folder called "constants" with a bunch of files inside and the "constants.dart" as the import file, then in the lib root itself I have "constants.dart" with a line inside export "constants/constants.dart";. Then I just created a shortcut snippet in VSCode with prefix "_iconst" that creates such import for me import 'package:<your_app_name>/constants.dart' as Constants;
  • badelectron77
    badelectron77 almost 4 years
    This approach doesn't work for me. 'constants.dart' without path will not be found because it's not in the same folder. Not even when it's located directly in /lib.
  • Nikhil Pathania
    Nikhil Pathania almost 4 years
    What if you want to import a single constant like JS?
  • TGLEE
    TGLEE over 3 years
    But doesn't using 'static const' keyword lead to the memory issue? how come?
  • Günter Zöchbauer
    Günter Zöchbauer over 3 years
    Why do you think that? The difference is that const makes it part of the data section of the executable and non-const makes code that can create an instance part of the code section (when compiled to native code). That would require more memory for non-const after instances are created. Dart also canonicalizes const values. If you invoke a const constructor multiple times with the same parameter values, spread over your apps code, it will return the same instance every time.
  • TGLEE
    TGLEE over 3 years
    I'm just concerned that using too many static const variables might take up too much space in the heap memory because it's static after all.
  • Günter Zöchbauer
    Günter Zöchbauer over 3 years
    The code instructions to create the objects at runtime won't take less space. As long as you don't add large BLOBS, this won't be an issue and you can't create consts in a for loop either. If you need to add every const individually and manually you'll have a hard time making this show up in memory usage.
  • Hyung Tae Carapeto Figur
    Hyung Tae Carapeto Figur over 3 years
    Dart documentation says explicitly "AVOID defining a class that contains only static members." dart.dev/guides/language/effective-dart/design
  • emkarachchi
    emkarachchi over 3 years
    what is the use of library constants;
  • Anirudh
    Anirudh over 3 years
    It let's dart know that the file is a library stackoverflow.com/questions/10157598/…
  • akshay bhange
    akshay bhange over 3 years
    should I create multiple libraries for eg. for colors, strings, sizes and other stuff like api related ?
  • user3808307
    user3808307 over 3 years
    I am doing this and using the constant in a switch statement and get Case expressions must be constants
  • Abhishek Jain
    Abhishek Jain over 3 years
    @Anirudh this would work exactly as is, without the library constants; line. What extra stuff does that do?
  • Anirudh
    Anirudh over 3 years
    library is a dart keyword that tells dart the file you are declaring is a library. Which is why dart lets you import the file into other files. This answer talks a bit more about this: stackoverflow.com/questions/12951989/…
  • Anirudh
    Anirudh over 3 years
    Turns out library constants; does pretty much nothing
  • html_programmer
    html_programmer about 3 years
    True. The fact my IDE doesn't recognise it is a fat downer. Not being able to auto import and having to type 'import' is just not done in this time.
  • Tek Yin
    Tek Yin about 3 years
    But on the same page, it also said this "However, this isn’t a hard rule. With constants and enum-like types, it may be natural to group them in a class." This means that it's ok to store static string or color variables inside a class
  • Hyung Tae Carapeto Figur
    Hyung Tae Carapeto Figur almost 3 years
    But with that approach, they won't be constants and won't get the benefits of constants, causing it to use more memory and to have to make a few more steps to get it in each build.
  • Magnus
    Magnus over 2 years
    And just below that, the documentation says explicitly "However, this isn’t a hard rule. With constants and enum-like types, it may be natural to group them in a class.".
  • Hyung Tae Carapeto Figur
    Hyung Tae Carapeto Figur over 2 years
    @Magnus Yes, but you can see the example they put there, it is an enum-like type. It is easier to organize like that, and you will not instantiate it. instead, you will only call MyClass.myConstant. But when you make it like a widget, then you will use unnecessary space in memory, not getting the benefits of the constants.
  • Magnus
    Magnus over 2 years
    I'm not sure what you mean, I didn't say anything about widgets? The question is specifically asking about how to store constants, and using a class with static constants - as your example MyClass.myConstant - would be a perfectly good way to do it.
  • Hyung Tae Carapeto Figur
    Hyung Tae Carapeto Figur over 2 years
    @Magnus Sorry for not being specific in my answer, that I'm referring to the accepted answer approach. I just wanted to diverge from the accepted answer here. And the most voted answer is about putting everything together in a single file, and I'm just saying that it is more organized if you put in separated files for big projects. But of course, you can use the MyClass.myConstant when it becomes more organized in an enum-like syntax, specially if you can do it in a way it wont become one more distraction in the code, in order to keep readability.
  • West
    West over 2 years
    I used the most voted and autocomplete also shows up in Android studio
  • Jahn E.
    Jahn E. over 2 years
    Useful answer, however, it is recommendet to use lowercase_with_underscores when specifying a library prefix.
  • mister_cool_beans
    mister_cool_beans about 2 years
    there are no constants declared in your example
  • BambinoUA
    BambinoUA almost 2 years
    What you suggest here are not constants! The benefit of constant they are allocated on compile time. But you approach will allocate memory on each "constant" access.