Seth Ladd
Seth Ladd

Reputation: 120449

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

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?

Upvotes: 389

Views: 353403

Answers (21)

Priyanshu Sidar
Priyanshu Sidar

Reputation: 146

There are two ways to do this in :

  1. you can use the initialValue parameter of TextFormFiled like:

     TextFormField(
         initialValue: "Hello",
     )
    
  2. you can use a TextEditingController and use its text parameter to pass initial value for the TextFormField like:

    Define TextEditingController with initial value:

    TextEditingController nameController = TextEditingController(text : "Hello")

    Pass the TextEditingController to TextFormField:

     TextFormField(
        controller : nameController,
     )
    

Both the ways cannot be used simultaneously as you cannot have initialValue and controller parameter defined at the same time.

Personally, I prefer the 2nd option as it also provides you freedom to further write logic for the TextFormField and customize it.

Upvotes: 6

Karma
Karma

Reputation: 595

final TextEditingController _textFieldController = TextEditingController();
@override
void initState() {
  _textFieldController.text = "Hello";
  super.initState();
}

Upvotes: 2

The best way would be replacing TextField to TextFormField because, we can use the property initialValue and avoid the complexity to manage state.

Using TextEditingControlleris not optimal because it needs to recreate a instance of TextEditingController just to pass a initial value. Additionally, how can you handle if you need to customize more and require access the text controller in other places ? It would be so confused

Upvotes: 0

Anandh Krishnan
Anandh Krishnan

Reputation: 5986

If you use TextEditingController just use the line in your class.

TextEditingController txtController = TextEditingController(text: 'Initial value')

TextField(
  controller: txtController,
);

If you don't use TextEditingController just go for initialValue

TextFormField(
      initialValue: 'your initial text',
  );

Full code

class _TestScreen extends State<Test> {
  TextEditingController _controller;

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

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
       TextFormField(       // First method
          initialValue: "Initial text"
        ),
       TextField(       // Second method
          controller: _controller, // Controller has the initial value
        ),
        
      ],
    );
  }
}

Upvotes: 7

Ebuzer SARIYERLİOĞLU
Ebuzer SARIYERLİOĞLU

Reputation: 818

you can use this code sample:

    TextFormField(
          controller: nameController?..text='Your initial value',
         
        ),

Upvotes: 2

manoj kumar
manoj kumar

Reputation: 31

if you use text form field and pass data from previous page to next page text form field use this

class ProfilePage extends StatefulWidget {

  late final String fname;

    ProfilePage({required this.fname});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final _form = GlobalKey<FormState>();
  
  late var FullNameController = TextEditingController(text: widget.fname);
  
}

Upvotes: 3

Abdur Rehman
Abdur Rehman

Reputation: 535

As for the above-mentioned answers all are right, but one thing is missing that I wanna add to it is how to customize the style of this default text of TextFormField.

TextEditingController textController = TextEditingController(text: '4');

 TextFormField(
    controller: textController,
     // This style property will customize the default controller text
    style: TextStyle(
    color: Colors.white,
    fontSize: 18,
    fontWeight: FontWeight.bold,
   ),
    ),

For this scenario, I would prefer to use TextEditingController instead of initialValue, Because if you want to change it later or modify it, then textController will continuously listen for your TextFormField input changes. This is my personal view, let me know if I am wrong.

Upvotes: 2

Neeraj
Neeraj

Reputation: 2558

Since none of the answers mention it, the TextEditingController should be disposed off after use. As in:

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();
  }
}

Upvotes: 6

Shirsh Shukla
Shirsh Shukla

Reputation: 5973

  1. When you are Using TextEditingController

If you use TextEditingController, set its text field to the desired value

TextEditingController txtController = TextEditingController()..text = 'Your initial text value'; 
TextField( controller: txtController ..... ) 
  1. When you are Not Using TextEditingController

If you are not using the TextEditingContller, use the initialValue field directly from the TextField widget:

TextFormField( initialValue: "Your initial text value" )

Upvotes: 4

Pawan Meena
Pawan Meena

Reputation: 121

Easy and Efficient way

Assign controller to your TextFormField or TextField and in initState you can initialise it to the initial value like this

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

Upvotes: 6

Apoorv Pandey
Apoorv Pandey

Reputation: 2501

You can do all of the above things but, if you want the API to show your data when its's get loaded it shows up like profile page. so here's the code:

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

I hope it clears everything. Happy coding!

Upvotes: 1

Debasmita Sarkar
Debasmita Sarkar

Reputation: 6589

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 widget automatically.

TextFormField(
  initialValue: 'initial value'
)

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

Upvotes: 38

ISRAEL RODRIGUES
ISRAEL RODRIGUES

Reputation: 101

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...'),
      ),
    );
  }
}

Upvotes: 10

Kent
Kent

Reputation: 2547

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"),
)

Upvotes: 71

Amir Ali Aghamali
Amir Ali Aghamali

Reputation: 642

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

or

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

Upvotes: 8

vovahost
vovahost

Reputation: 35997

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) => {},
)

Upvotes: 209

BIS Tech
BIS Tech

Reputation: 19424

inside class,

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

TextField,

   child: new TextField(
        controller: usernameController,
    ...
)

Upvotes: 5

Sami Kanafani
Sami Kanafani

Reputation: 15741

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

TextFormField(initialValue: "I am smart")

Upvotes: 288

Nirav Bhavsar
Nirav Bhavsar

Reputation: 2233

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

Upvotes: 49

Muaad
Muaad

Reputation: 376

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.

Upvotes: 15

Seth Ladd
Seth Ladd

Reputation: 120449

(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'),
        ),
      ],
    );
  }
}

Upvotes: 219

Related Questions