updating text field in flutter on button click updating text field in flutter on button click dart dart

updating text field in flutter on button click


I do not really understand what is the desired output you want, but this example may be helpful to show you where things went wrong in your code.

enter image description here

class TextFieldEx extends StatefulWidget {  @override  _TextFieldExState createState() => new _TextFieldExState();}class _TextFieldExState extends State<TextFieldEx> {  TextEditingController _c ;  double _metal = 0.0;  double _total = 0.0;  String _text = "initial";  @override  void initState() {      _c = new TextEditingController();      super.initState();    }  @override  void dispose(){   _c?.dispose();   super.dispose();  }  @override  Widget build(BuildContext context) {    return new Scaffold(      body: new Center(        child: new Column(          mainAxisAlignment: MainAxisAlignment.center,          children: <Widget>[            new TextField(              keyboardType: TextInputType.number,              onChanged: (v)=>setState((){_text=v;}),              controller: _c,            ),            new RaisedButton(              child: new Text("Update"),              onPressed: (){                setState((){                  _metal = double.parse(_c.text);                  _total = _metal+0.025;                  _c.text = "";                });              },            ),            new Text("Text Input: $_text"),            new Text("Metal :$_metal"),            new Text("Total:$_total")          ],        )      )    );  }}


There is lot of problem with your code.

  1. If you want to read data from TextField use controller.
  2. On Button Pressed do calculation in setState() method.
  3. As you want to show the calculated value again in the Text, you must have to create a StateFullWidget so that, on calling setState() it will get re rendered and updated value will be shown.

I hope it will help you.