Prime Alexander
Prime Alexander

Reputation: 35

How to initialize a textfield in flutter

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

Upvotes: 1

Views: 831

Answers (1)

user12152162
user12152162

Reputation:

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.

Upvotes: 1

Related Questions