在Flutter中保持所有常数的最佳实践是什么? [英] What's the best practice to keep all the constants in Flutter?

查看:53
本文介绍了在Flutter中保持所有常数的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



What's the best programming practice to


在Flutter中创建常量类的最佳编程做法是什么

create a constant class in Flutter

保留所有应用程序常数以便于参考。我知道Dart中有 const 关键字用于创建常量字段,但是可以将 static 与const一起使用,否则会在运行时创建内存问题。

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


推荐答案

编辑

现在,标志-dart-define 已添加到Flutter的不同命令行中,以下答案为否-longer适用。

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倾向于 not 具有任何全局/静态变量并使用InheritedWidget。

Flutter tend to not have any global/static variables and use an InheritedWidget.

这意味着您可以编写:

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(),
    ),
  );
}

并按以下方式使用:

@override
Widget build(BuilContext context) {
  return Text(MyConstants.of(context).successMessage);
}




此代码比 static const ,但具有许多优点:


  • 与热重载一起使用

  • 易于测试和模拟

  • 可以用比常量更具动态性的东西替换,而无需重写整个应用程序。

但同时,它:


  1. 不消耗太多内存(继承的窗口小部件通常创建一次)

  2. 是表演者(获得InheritedWidget为O(1))

这篇关于在Flutter中保持所有常数的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆