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

前端 未结 10 857
南笙
南笙 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:31

    If you want to handle multiple TextInputs as asked by @MRT in the comment to the accepted answer, you can create a function that takes an initial value and returns a TextEditingController like this:

    initialValue(val) {
      return TextEditingController(text: val);
    }
    

    Then, set this function as the controller for the TextInput and supply its initial value there like this:

    controller: initialValue('Some initial value here....')
    

    You can repeat this for the other TextInputs.

    0 讨论(0)
  • 2021-01-30 12:32
    class _YourClassState extends State<YourClass> {
      TextEditingController _controller = TextEditingController();
    
      @override
      void initState() {
        super.initState();
        _controller.text = 'Your message';
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          color: Colors.white,
          child: TextFormField(
            controller: _controller,
            decoration: InputDecoration(labelText: 'Send message...'),
          ),
        );
      }
    }
    
    0 讨论(0)
  • 2021-01-30 12:34

    inside class,

      final usernameController = TextEditingController(text: 'bhanuka');
    

    TextField,

       child: new TextField(
            controller: usernameController,
        ...
    )
    
    0 讨论(0)
  • 2021-01-30 12:35

    This can be achieved using TextEditingController.

    To have an initial value you can add

    TextEditingController _controller = TextEditingController(text: 'initial value');
    

    or

    If you are using TextFormField you have a initialValue property there. Which basically provides this initialValue to the controller automatically.

    TextEditingController _controller = TextEditingController();
    TextFormField(
      controller: _controller,
      initialValue: 'initial value'
    )
    

    To clear the text you can use _controller.clear() method.

    0 讨论(0)
  • 2021-01-30 12:35
    TextEdittingController _controller = new TextEdittingController(text: "your Text");
    

    or

    @override
      void initState() {
        super.initState();
        _Controller.text = "Your Text";
        }
    
    0 讨论(0)
  • 2021-01-30 12:36

    I've seen many ways of doing this on here. However I think this is a little more efficient or at least concise than the other answers.

    TextField(
       controller: TextEditingController(text: "Initial Text here"),
    )
    
    0 讨论(0)
提交回复
热议问题