How to initialize a textfield in flutter

633

That is quite simple, I will show you an example that you can follow.

Example:

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}
class HomePageState extends State<HomePage> {
  // creating and initilizing a counter variable 
 int _counter = 0;
TextEditingController _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body:  new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new TextField(
            controller: _controller,
            decoration: new InputDecoration(labelText: "Enter your number"),
            keyboardType: TextInputType.number,
          ),
          FlatButton(
          onPressed:(){
           _counter = int.parse(_controller.text);
              },
             child: Text('Press Me!'),
            )
        ],
      ));
  }
}

At first, I created a counter and initialize it with '0' and then I created a controller which I will use for controlling the TextField. After that, I created a TextField widget and passed the _controller to it. I used the controller because I need to fetch data from the TextField so do we. We fetched data from the _controller via _controller.text which returns a string. Although we create the counter as an integer, we can't pass a string to it. So, I changed the data that we fetched from the _controller into an integer using int.parse(_controller.text) and then we passed it to the _counter variable.

Note: I had specified the keyboardType as TextInputType.number because we are dealing with numbers as you mentioned.

Share:
633
Author by

Prime Alexander

Updated on December 15, 2022

Comments

  • Prime Alexander less than a minute

    I am new to flutter and I’m trying to create a counter that begins from a user input and decrement but I can’t get an integer input from text field how can I initialize a user input to be an integer then add it to an int variable

    • Darish
      Darish about 3 years
      what you have tried? could please post your code?
    • Prime Alexander about 3 years
      Thank you so much for your concern I got the answer
  • Admin
    Admin about 3 years
    stop using ‘new’
  • Admin
    Admin about 3 years
    @Eugene exactly but he is a beginner so I thought it would be better to show him the old ways as well :D