Do stateless widgets dispose on their own?

最后都变了- 提交于 2020-07-06 09:55:13

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/55549663/do-stateless-widgets-dispose-on-their-own

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!