Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating text field in flutter on button click

Tags:

flutter

dart

I'm developing an app on flutter, on main screen i have a button which open another screen which is inside a method. on that screen i want so to do some calculation like taking user input and updating text field, on clicking the button the method calculateAmount called which updates variable total which reflects on text field but text field is not updating, it only updates on pressing finished on keyboard... how can achieve this task. here is my code:

    import 'package:flutter/material.dart';
    void main() {

      runApp(new MaterialApp(
          debugShowCheckedModeBanner: false,
        home: new homePage()
      ));
    }

    class homePage extends StatefulWidget {

      @override
      homePageState  createState() => new homePageState();
    }
    class homePageState extends State<homePage> {

    double metal = 0.0;
    double total = 0.0;

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("APP-Title",), backgroundColor: Colors.orange),
           body: new Container(
            child: new Center(
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[

                    new Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[

                        new Expanded(child: new RaisedButton.icon(
                          color: Colors.orange,
                          icon: const Icon(
                            Icons.info, size: 25.0, color: Colors.white,),
                          label: new Text('Calculate', style: new TextStyle(
                              color: Colors.white
                              )),
                          onPressed: () {
                            calculateWindow();
                          ),),
                   ],
                )
              ],
            )
        ),
      ),
    );
  }
 void calculateWindow(){
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          return new Scaffold(
            appBar: new AppBar(
              title: new Text('Calculator'),
              backgroundColor: Colors.orange,
            ),
            body: new ListView(
              children: <Widget>[

                new Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    new Container(
                      height: 50.0,
                      width: 360.0,
                      decoration: new BoxDecoration(
                        color: Colors.orange,
                        shape: BoxShape.rectangle,
                      ),
                      child: new Center(
                        child: new Row(
                          children: <Widget>[
                            new Expanded(
                              child: new Container(
                                child:  new Text("Gold & Silver in Sold & Ornaments",
                                  style: textStyle,
                                  textAlign: textAlign
                                ),
                              ),
                            ),
                            new Container(
                              height: 40.0,
                              width: 80.0,
                              decoration:  new BoxDecoration(
                                  color: Colors.white),
                              child: new TextField(
                                  keyboardType: TextInputType.number,
                                  onSubmitted : (String value) {
                                    try {
                                      metal = double.parse(value.toString());
                                      print(total);
                                    } catch (exception) {
                                      metal = 0.0;
                                    }
                                  }
                              ),
                            ),
                          ],
                        ),
                      ),
                      ),

                  ],
                new Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    new Expanded(
                      child: new Container(
                          width: 50.0,
                          child: new RaisedButton.icon(
                            color: Colors.grey,
                            icon: const Icon(
                              Icons.check, size: 25.0, color: Colors.white,),
                            label: new Text('Calculate', style: new TextStyle(
                                color: Colors.white,
                               )),
                            onPressed: calculateAmount,
                          ),
                      ),
                    ),
                  ],
                ),
                new Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    new Container(
                      height: 50.0,
                      width: 350.0,
                      decoration: new BoxDecoration(
                        color: Colors.blueGrey,
                        shape: BoxShape.rectangle,
                      ),
                      child: new Center(
                        child: new Row(
                          children: <Widget>[
                            new Expanded(
                              child: new Container(
                                child:  new Text("Total Amount:",
                                  style: new TextStyle(
                                  color: Colors.white,),
                                  textAlign: TextAlign.left,),
                              ),
                            ),
                            new Container(

                              child: new Text(
                                '$total',
                                textAlign: TextAlign.left,
                                overflow: TextOverflow.ellipsis,
                                style: textStyle,
                                textDirection: TextDirection.ltr,
                              )
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          );
        },
      ),
    );
  }
 void calculateAmount(){

    setState((){
      total =  metal + 0.025;

    });
  }
}
like image 720
Arib Yousuf Avatar asked Apr 27 '18 05:04

Arib Yousuf


People also ask

How do you auto fill TextField in Flutter?

Add the Auto-fill hint using constants form AutofillHints class as a list. even if you only have one Hint, you have to add it as a single item in a list. TextFormField after Auto-fill hint added. For a complete list of supported auto-fill hints in flutter refer to this documentation.


2 Answers

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")
          ],
        )
      )
    );
  }
}
like image 137
Shady Aziza Avatar answered Sep 21 '22 15:09

Shady Aziza


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.

like image 28
Dhrumil Shah - dhuma1981 Avatar answered Sep 20 '22 15:09

Dhrumil Shah - dhuma1981