首页 > 解决方案 > 在 Textfield 输入后 Flutter Text 不会进一步更新

问题描述

我有箭头按钮来增加或减少一个age可以正常更新的变量hintText,但是如果我使用TextField小部件输入一个新值,它会更新得很好,但是之后箭头按钮不再起作用以进一步改变年龄值hintText. _

但是,该值仍在幕后更新,可以通过print函数查看。

这是所用代码的简化版本:

TextField(
    onChanged: (val) {
          setState(() {
            age = int.parse(val);
          });,
    keyboardType: TextInputType.number,
    decoration: InputDecoration(
    border: InputBorder.none,
    hintText: age.toString(),
    hintStyle: TextStyle(
        color: Color(0xFF999999), fontWeight: FontWeight.bold),
  ),
)


Container(
      child: RawMaterialButton(
        onPressed: chngAge,
)


void chngAge() {
    setState(() {
      age++;
    });
  }

我想知道是否在将某些文本输入到文本字段后它不再更长hintText,因此无法以这种方式更新?

标签: flutterdart

解决方案


您需要的是更改您的数据而TextField不是hint值,因为当您将一些文本写入您的TextField时,提示会消失。

这是我做的一个例子:

class SampleText extends StatefulWidget {
  @override
  _SampleTextState createState() => _SampleTextState();
}

class _SampleTextState extends State<SampleText> {
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.plus_one),
        onPressed: chngAge,
      ),
      body: Center(
        child: TextField(
          controller: _controller,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintStyle: TextStyle(
                color: Color(0xFF999999), fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

  void chngAge() {
    _controller.text = (int.parse(_controller.text) + 1).toString();
  }
}

您可以在此处获取更多信息:https ://flutter.dev/docs/cookbook/forms/retrieve-input


推荐阅读