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

前端 未结 8 488
终归单人心
终归单人心 2021-01-30 02:11

What\'s the best programming practice to

create a constant class in Flutter

to keep all the application constants for easy referenc

8条回答
  •  广开言路
    2021-01-30 02:35

    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.

提交回复
热议问题