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

穿精又带淫゛_ 提交于 2020-01-22 04:53:05

问题


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.";
}

回答1:


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))



回答2:


My preferred solution is to make my own Dart library.

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

library Constants;

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

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

import 'constants.dart' as Constants;

You may need to run flutter pub get for the file to be recognized. And now you can easily access your constants with this syntax:

String a = Constants.SUCCESS_MESSAGE;



回答3:


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



来源:https://stackoverflow.com/questions/54069239/whats-the-best-practice-to-keep-all-the-constants-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!