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

查看:18
本文介绍了在 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.";
}

推荐答案

编辑

既然标志 --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天全站免登陆