Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

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

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.";
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...