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

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

问题描述

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(),
)

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

解决方案

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

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:

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();
  }
}

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天全站免登陆