Search code examples
flutteruser-input

How to get Integer value from a user through a TextField that uses an onChanged method in Flutter


It's worth noting that I am quite new to flutter so a lot of work done is based on tutorials or videos... Apologies if the question seems obvious.

//Build Length Box.
Widget buildLength() => buildHeader(
        header: 'House Length: ',
        child: Row(
          children: [
            // I want to be able to get user input(has to be an integer value for calculations further in the program)
            // from this child: Text(), At the moment I am only able to get the input from the slider...
            //I want to be able to use the slider or the text next to it.
            //The first child widget should preferably work with the same onChangedLength method the slider uses...
            Expanded(
              flex: 1,    
              child: Text(
                length.toString(),
                style: TextStyle(color: Colors.white),
              ),
            ),

            Expanded(
              flex: 9,
              child: Slider( //TODO: Decide on the correct parameters for the slider, min/max/etc...
                label: length.toString(),
                value: (length ?? 0).toDouble(),
                min: 0,
                max: 100,
                divisions: 100,
                onChanged: (length) => onChangedLength(length.toInt()),
              ),
            ),
          ],
        ),
      );

The onChanged Method was mentioned here as well.

onChangedLength: (length) => setState(() => this.editLength = length),

The tutorial I am busy with uses the onChanged, however if this wont work I am open to other methods I can use.


Solution

  • You are setting the changed value of the length into editLength. yet you using length.toString() to display, if your declared variable is int editLength

    editLength.toString() // Text Widget
    label: length.toString(), // Slider Widget
    value: (editLength ?? 0).toDouble() // Slider Widget
    

    or if your declared variable is int length

    onChanged: (newLength) => onChangedLength(newLength.toInt()), // Slider widget
    onChangedLength(newLength) => setState(() => this.length = newLength); // onChangedLength function