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

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

问题描述

最佳编程实践是什么

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

推荐答案

EDIT

既然标记 --dart-define 已添加到 Flutter 的不同命令行中,以下答案不再适用.

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.

虽然 static const 没有技术问题,但在架构上您可能希望采用不同的方式.

While there are no technical issues with static const, architecturally you may want to do it differently.

Flutter 倾向于没有任何全局/静态变量并使用 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 有更多的代码,但提供了许多优点:


This has a bit more code than the static const, but offer many advantages:

  • 适用于热重载
  • 易于测试和模拟
  • 可以替换为比常量更动态的东西,而无需重写整个应用程序.

但同时它:

  1. 不消耗更多内存(继承的小部件通常创建一次)
  2. 性能良好(获取 InheritedWidget 是 O(1))

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

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