在Flutter的StatelessWidget中使用TextEditingController可以吗? [英] Is it okay to use TextEditingController in StatelessWidget in Flutter?

查看:103
本文介绍了在Flutter的StatelessWidget中使用TextEditingController可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不需要使用TextEditingController做很多事情,但想显示初始文本.我觉得为此创建StatefulWidget太过分了.这就是我希望我的代码看起来像

I don't need to do many things with TextEditingController but want to show the initial text. And I feel like creating StatefulWidget is too much for that. Here's what I want my code looks like

// In StatelessWidget
TextField(
    controller: TextEditingController(),
)

但是我见过的每一篇教程和博客文章都在StatefulWidget中使用TextEditingController并将它们放在dispose方法中.但是,如果我像上面那样使用的话,我将无法处置它们.

But every tutorials and blog posts I've seen use TextEditingController in StatefulWidget and dispose them in the dispose method. But I can't dispose them if I use like the above

推荐答案

如果您想使用 TextEditingController ,除了使用 StatefulWidget 之外,别无选择想要避免内存泄漏.

If you want to use TextEditingController, there is no way around except to use a StatefulWidget if you want to avoid memory leaks.

但是,如果您在这种方法中看到很多样板,则可以使用 HookWidget ( flutter_hooks ),它使您能够以简单的方式访问 TextEditingController 并为您处理,以下是一个比较:

However, if you see alot of boilerplate in this approach, you can use HookWidget (flutter_hooks) which gives you access to TextEditingController in a simple way and disposes it for you,here is a comparison:

使用 StatefulWidget :

using StatefulWidget:

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  TextEditingController controller;
  FocusNode focusNode;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.red,
          child: TextField(
            focusNode: focusNode,
            controller: controller,
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    controller = TextEditingController();
    focusNode = FocusNode();
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    focusNode.dispose();
    super.dispose();
  }
}

使用 HookWidget :

using HookWidget:

class Test extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final focusNode = useFocusNode();
    final controller = useTextEditingController();
      return Scaffold(
      body: Center(
        child: Container(
          width: 200,
          height: 200,
          color: Colors.red,
          child: TextField(
            focusNode: focusNode,
            controller: controller,
          ),
        ),
      ),
    );
  }
}

这篇关于在Flutter的StatelessWidget中使用TextEditingController可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆