如何通过在 Flutter 中使用 onChanged 方法的 TextField 从用户获取整数值

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

值得注意的是,我对 flutter 还很陌生,所以很多工作都是基于教程或视频...... 如果问题看起来很明显,我们深表歉意。

//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()),
              ),
            ),
          ],
        ),
      );

这里也提到了 onChanged 方法。

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

我忙于使用的教​​程使用 onChanged,但是如果这不起作用,我愿意接受我可以使用的其他方法。

您正在将更改后的长度值设置到 editLength 中。 但是您使用 length.toString() 来显示, 如果您声明的变量是 int editLength

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

或 如果你声明的变量是 int length

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