flutter TextField关闭软键盘时清除掉输入的内容

flutter TextField关闭软键盘时清除掉输入的内容

如上图所示,在TextField中输入内容后,关闭软键盘时都会清空掉输入框里的内容

代码如下

  @override
  Widget build(BuildContext context) {
    print('ChangePasswordForm  Widget build(BuildContext context)');
    TextEditingController controller = TextEditingController();
    return BlocListener<ChangePasswordBloc, ChangePasswordState>(
        listener: stateListener,
        child: Scaffold(
          backgroundColor: ThemeColors.normalBackground,
          body: SingleChildScrollView(
            child: Column(
              children: [
                ......
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                          key: const Key('aaaaaaaaaaaa'),
                          controller: controller,
                          maxLines: 1,
                          cursorColor: ThemeColors.primaryValue,
                          style: AppTextStyle.mainText(),
                          decoration: InputDecoration(
                            hintStyle: AppTextStyle.promptText(),
                            contentPadding: EdgeInsets.only(left: 10,right: 10),
                            hintText: '请输入..',
                            border: InputBorder.none,
                          )),
                    ),
                    GestureDetector(
                      child: Text(
                        '搜索',
                        style: TextStyle(color: ThemeColors.primaryValue),
                      ),
                      onTap: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        print('搜索内容:${controller?.text}');
                      },
                    )
                  ],
                ),
              ],
            ),
          ),
        ));
  }

我需要在点击搜索时,获取的输入的内容去搜索,所以就在TextField中传入了controller

后来观察打印的日志,发现每次弹出、收起软键盘时。build()方法都会调用,每次build的时候,controller都是个新的对象。之前输入的内容,新的controller不会持有。所以把TextEditingController的初始化放到了initState()方法里,如下所示

TextEditingController _controller;
@override
void initState() {
  print('ChangePasswordForm  initState()');
  _controller = TextEditingController();
}

然后TextField的controller参数传入这个_controller
运行后收起软键盘,之前输入的内容就不会被清空了

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值