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

前端 未结 8 466
终归单人心
终归单人心 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:34

    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.

    In this example:

    You could use a relative path:

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

    Or an absolute path from the lib directory:

    import 'package:/assets/constants.dart' as Constants;
    

    Now you can easily access your constants with this syntax:

    String a = Constants.SUCCESS_MESSAGE;
    

提交回复
热议问题