Do stateless widgets dispose on their own?

Rick picture Rick · Apr 6, 2019 · Viewed 18.6k times · Source

I created a PostUpdaterWidget extending StatelessWidget which makes use of TextEditingControllers for testing out implementation of Bloc Pattern.

final _usernameController = TextEditingController();
  final _contentController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        TextField(
          controller: _usernameController,
          decoration: InputDecoration(hintText: "Post Username"),
        ),
        TextField(
          controller: _contentController,
          decoration: InputDecoration(hintText: "Post Content"),
        ),
        Container(
          height: 16,
        ),
        RaisedButton(
          child: Text("Update Post"),
          onPressed: () => _updatePost(context),
        )
      ],
    );
  }

  _updatePost(BuildContext context) {
    print("Processing Post Update");
    String username = _usernameController.text.trim();
    String content = _contentController.text.trim();

    Post post = new Post();
    post.id = id;
    post.username = username;
    post.content = content;

    id += 1;

    print("Dispatching Post Update");
    BlocProvider.of<PostBloc>(context).updatePost(post);
  }

I have seen in a lot of examples that controllers should be disposed. However there is no method to override a dispose function in a StatelessWidget.

I have thought of creating its own dispose function to dispose the controllers used, and just create a variable of this widget for those that will use this widget so that I can call the dispose function.

But I want to know first whether I really need to do that, or this StatelessWidget actually disposes on its own.

Should I proceed with my idea? Or just leave it be, since it might be disposing these controllers on its own, so that I should not be concerned of memory leaks.

Answer

Suragch picture Suragch · Jan 22, 2020

This question seems to indicate that objects are not disposed when the StatelessWidget gets destroyed, at least not immediately. In any case, when you are using a TextEditingController (or maintaining any mutable state), then you should use a StatefulWidget and keep the state in the State class. The State class has a dispose() method that you can use (as you mentioned in your question).

Otherwise, if you use a StatelessWidget, you lose your state every time the UI gets rebuilt. StatefulWidgets keep their state across rebuilds because the state is in the State class, not in the widget. See also this answer.