Search code examples
flutterflutter-layoutflutter-listviewflutter-text

Update Text() based on user input in a TextFormField() within a container in a ListVIew


I'm new to flutter and have a ... challenge with the above.

I retrive data about several objects / documents from FireStore and create a ListView.

The logic, or lack there of, look like this:

Container
    StreamBuilder
         ListView
             Container
                 Rows, Columns, Text and whatever to display each document from StreamBuilder.

This ListView contains several Containers where each Container display data from one object. Within each Container there is a TextFormField that takes a double. Based on this value, I want to change a Text() within the same container - a calculation.

Is this possible? If so - how? I understand I can use TextEditController somehow, but then the result of tha calculation will be editable. Or?

return new ListView(//
  children: getMedicationItem(asyncSnapshot
    shrinkWrap: true,
    children: asyncSnapshot.data.documents.map((DocumentSnapshot document) {
      MyObject object = new MyObject(document, integerValue);
      backgroundColor = !backgroundColor;
      return new Container(
        color: backgroundColor? Colors.black26: Colors.white,
          child: new Row(
            children: <Widget>[
              new Flexible(
                child: TextFormField(
                  onChanged: (text) {
                    double calculation = 0.0;
                    if (text.length > 0)
                      calculation = double.tryParse(text) * 23;
                    **UPDATE "$calculation" in Text() below** 
                  },
                  keyboardType: TextInputType.number,
                  inputFormatters: [_decimal_validator],
                )
              ),
              new Flexible(
                child: Text("$calculation"),
              )
            ]
          ),
        );
      }
    ).toList(),
  )
);

Solution

  • All you should need to do is use a setState to tell Flutter that the variable has changed and you want whichever Widgets that use it rebuilt:

    if (text.length > 0){
      setState((){
        calculation = double.tryParse(text) * 23;
      });
    }