gpt4 book ai didi

flutter - 在 Flutter 中不将 MethodChannels 设置为静态常量有缺点吗?

转载 作者:行者123 更新时间:2023-12-03 04:58:35 25 4
gpt4 key购买 nike

Flutter docs 中的示例将他们正在使用的 MethodChannel(与 native 主机通信)直接在使用它的 Widget 中声明为 static const。为了将其中一些分离,我正在尝试布局我的应用程序,以便 MethodChannel

  1. 驻留在 BLoC 甚至底层服务层中,而不是直接驻留在 Widget 中,并且
  2. 被注入(inject),使一切都容易单元测试。

如果 MethodChannel 不是 staticconst,是否会出现问题(与性能相关,导致错误等)?

最佳答案

定义它的 MethodChannel 实例按照约定是 const,老实说,没有理由不这样做。然而,虽然典型的实现在服务类中定义了 channel ,但并非必须如此。您还可以轻松地在别处定义它,然后通过依赖注入(inject)将它传递给您的服务类。

DI 初始化文件

const platform = MethodChannel(...);

void initDI() {
GetIt.I.registerSingleton(platform, "MyMethodChannel");
}

服务文件

class PlatformService {
final MethodChannel platform;

PlatformService()
: platform = GetIt().I.get("MyMethodChannel");

...
}

关于flutter - 在 Flutter 中不将 MethodChannels 设置为静态常量有缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60080431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com