How do I supply an initial value to a text field?

前端 未结 10 873
南笙
南笙 2021-01-30 12:15

I\'d like to supply an initial value to a text field and redraw it with an empty value to clear the text. What\'s the best approach to do that with Flutter\'s APIs?

相关标签:
10条回答
  • 2021-01-30 12:44

    You don't have to define a separate variable in the widget scope, just do it inline:

    TextField(
      controller: TextEditingController()..text = 'Your initial value',
      onChanged: (text) => {},
    )
    
    0 讨论(0)
  • 2021-01-30 12:49

    You can use a TextFormField instead of TextField, and use the initialValue property. for example

    TextFormField(initialValue: "I am smart")
    
    0 讨论(0)
  • 2021-01-30 12:49

    If you are using TextEditingController then set the text to it, like below

    TextEditingController _controller = new TextEditingController();
    
    
    _controller.text = 'your initial text';
    
    final your_text_name = TextFormField(
          autofocus: false,
          controller: _controller,
          decoration: InputDecoration(
            hintText: 'Hint Value',
          ),
        );
    

    and if you are not using any TextEditingController then you can directly use initialValue like below

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

    For more reference TextEditingController

    0 讨论(0)
  • 2021-01-30 12:54

    (From the mailing list. I didn't come up with this answer.)

    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'),
            ),
          ],
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题