如何将 Flutter slider double 值转换为 int

Zoh*_*riq 1 dart flutter flutter-test flutter-layout

我正在为 BMI 计算器编写代码,我使用滑块来计算身高,它返回一个双精度类型和一个长类型。我尝试过_startHeight.toInt(),但没有成功。有没有办法在不使用除法的情况下显示标签。

这是我的滑块代码。

               Slider(
                  value: _startHeight,
                  min: 1,
                  max: 100,
                  onChanged: (newHeight) {
                    setState(() {
                      _startHeight = newHeight;
                      _startHeight.toInt();
                      print(_startHeight);
                    });
                  },
                ),
Run Code Online (Sandbox Code Playgroud)

谢谢。

Uj *_*orb 5

如果你想_startHeight成为一个,那么我假设你首先int将它定义为一个。int

您正在尝试将 a 分配double给 an int,然后将其更改doubleint。你需要以相反的方式来做:

onChanged: (double newHeight) {
  setState(() {
    _startHeight = newHeight.toInt();
    print(_startHeight);
  });
}
Run Code Online (Sandbox Code Playgroud)

如果您的最终目标是在没有小数的字符串中显示值,那么您可以使用toStringAsFixed

_startHeight.toStringAsFixed(0);

  • 非常感谢 _startHeight.toStringAsFixed(0); 效果很好。 (3认同)