geg
geg

Reputation: 4795

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 (e.g. an http service).

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. 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?

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. I want to save them as variables because it more clearly documents the dependencies.

Fetching in #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() {

  }
}

Upvotes: 0

Views: 113

Answers (1)

Robert Sandberg
Robert Sandberg

Reputation: 8627

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.

Upvotes: 2

Related Questions