简体   繁体   English

Flutter:是否可以在构建方法之外的 Widget 实例变量中存储依赖项?

[英]Flutter: Is it ok to store dependencies in Widget instance variables outside of the build method?

In my Flutter app I'm using get_it to retrieve non-widget related dependencies (eg an http service).在我的 Flutter 应用程序中,我使用get_it来检索与小部件无关的依赖项(例如 http 服务)。

Most of the Flutter Widget examples that I see don't save any variables in the widget class, but rather they retrieve them in the #build method.我看到的大多数 Flutter Widget示例都没有在小部件类中保存任何变量,而是在#build方法中检索它们。 This makes sense for dependencies that rely on the context , but for other dependencies that don't rely on context is it ok to save them as instance variables when the constructor is called?这对于依赖于context依赖是有意义的,但是对于其他不依赖于context依赖,是否可以在调用构造函数时将它们保存为实例变量?

I'm not very familiar with the Widget lifecycle so I'm not sure if this could lead to memory leaks, etc if widget instances are discarded.我对 Widget 生命周期不是很熟悉,所以我不确定这是否会导致内存泄漏等,如果小部件实例被丢弃。 I want to save them as variables because it more clearly documents the dependencies.我想将它们保存为变量,因为它更清楚地记录了依赖关系。

Fetching in #build#build获取

class MyWidget extends StatelessWidget {
  @override
  Widget build() {
    var myService = GetIt.instance.get<MyService>();
  }
}

Storing in instance variable存储在实例变量中

class MyWidget extends StatelessWidget {
  final MyService myService;

  MyWidget(): myService = GetIt.instance.get();

  @override
  Widget build() {

  }
}

I see no reason why you couldn't store them as an instance variable.我看不出为什么不能将它们存储为实例变量。

You obviously cannot dispose of instance variables in a manual/clean way and must rely on the garbage collector to do what it should.您显然不能以手动/干净的方式处理实例变量,必须依靠垃圾收集器来做它应该做的事情。 That could be seen as a drawback.这可以被视为一个缺点。 In your case I assume that isn't an issue since the service might live throughout the lifecycle of the app.在您的情况下,我认为这不是问题,因为该服务可能会贯穿应用程序的整个生命周期。

If you are very nervous about memory leaks, use a stateful widget and dispose the things needing disposal.如果您对内存泄漏非常紧张,请使用有状态的小部件并处理需要处理的东西。

If you very clearly want to document the dependencies you could go further and require it as a parameter to the widget.如果您非常清楚地想要记录依赖关系,您可以更进一步并将其作为小部件的参数。 It would also make the widget more easily testable.它还将使小部件更易于测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM