我想为文本字段提供一个初始值,并重新绘制一个空值以清除文本。用Flutter的api实现这一点的最佳方法是什么?


当前回答

TextEdittingController _controller = new TextEdittingController(text: "your Text");

or

@override
  void initState() {
    super.initState();
    _Controller.text = "Your Text";
    }

其他回答

由于没有一个答案提到它,TextEditingController应该在使用后被丢弃。如:

class MyWidget extends StatefulWidget {
  const MyWidget({Key? key}) : super(key: key);

  @override
  MyWidgetState createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {
  final myController = TextEditingController(text: "Initial value");

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: myController,
    );
  }

  @override
  void dispose() {
    // dispose it here
    myController.dispose();
    super.dispose();
  }
}

(来自邮件列表。这个答案不是我想出来的。)

class _FooState extends State<Foo> {
  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController(text: 'Initial value');
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new TextField(
          // The TextField is first built, the controller has some initial text,
          // which the TextField shows. As the user edits, the text property of
          // the controller is updated.
          controller: _controller,
        ),
        new RaisedButton(
          onPressed: () {
            // You can also use the controller to manipuate what is shown in the
            // text field. For example, the clear() method removes all the text
            // from the text field.
            _controller.clear();
          },
          child: new Text('CLEAR'),
        ),
      ],
    );
  }
}

你可以做以上所有的事情,但如果你想让API在加载时显示你的数据,它会像配置文件页面一样显示。下面是代码:

TextEditingController _nameController = TextEditingController(); // initialize the controller
 // when API gets the data, do this:
 _nameController.text = response.data.fullName; or _nameController.text = "Apoorv Pandey"

我希望这能澄清一切。编码快乐!

你可以使用TextFormField代替TextField,并使用initialValue属性。例如

TextFormField(initialValue: "I am smart")

如果你正在使用TextEditingController,然后设置文本为它,如下所示

TextEditingController _controller = new TextEditingController();


_controller.text = 'your initial text';

final your_text_name = TextFormField(
      autofocus: false,
      controller: _controller,
      decoration: InputDecoration(
        hintText: 'Hint Value',
      ),
    );

如果你不使用任何TextEditingController,那么你可以直接使用initialValue如下

final last_name = TextFormField(
      autofocus: false,
      initialValue: 'your initial text',
      decoration: InputDecoration(
        hintText: 'Last Name',
      ),
    );

更多参考TextEditingController