Flutter中如何跨Stateful Widget传递NumberPicker值并计算BMI
可以实现,具体操作步骤如下
1. 实现接收参数的ResultScreen
首先创建ResultScreen这个StatefulWidget,在其类中定义必填的身高、体重参数,确保参数能传递到状态类中使用:
class ResultScreen extends StatefulWidget { // 接收从HomeScreen传递来的身高(单位:厘米)和体重(单位:公斤) final int height; final int weight; const ResultScreen({ super.key, required this.height, required this.weight, }); @override State<ResultScreen> createState() => _ResultScreenState(); } class _ResultScreenState extends State<ResultScreen> { // 计算BMI的方法 double _calculateBMI() { // 将身高从厘米转换为米 double heightInMeters = widget.height / 100; // BMI公式:体重(kg) ÷ (身高(m) × 身高(m)) return widget.weight / (heightInMeters * heightInMeters); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('BMI计算结果')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( '你的BMI指数为:', style: TextStyle(fontSize: 20), ), const SizedBox(height: 20), Text( // 保留两位小数展示结果 _calculateBMI().toStringAsFixed(2), style: const TextStyle(fontSize: 36, fontWeight: FontWeight.bold), ), ], ), ), ); } }
2. 在HomeScreen中传递参数并导航
在HomeScreen中,当用户选择好身高和体重后,通过Navigator导航到ResultScreen时,将_currentValue1(身高)和_currentValue2(体重)作为参数传入:
class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { int _currentValue1 = 170; // 初始身高(厘米) int _currentValue2 = 65; // 初始体重(公斤) @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('BMI计算器')), body: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ // 身高选择器 NumberPicker( value: _currentValue1, minValue: 100, maxValue: 220, onChanged: (value) => setState(() => _currentValue1 = value), decoration: const InputDecoration( labelText: '身高(厘米)', border: OutlineInputBorder(), ), ), const SizedBox(height: 20), // 体重选择器 NumberPicker( value: _currentValue2, minValue: 30, maxValue: 150, onChanged: (value) => setState(() => _currentValue2 = value), decoration: const InputDecoration( labelText: '体重(公斤)', border: OutlineInputBorder(), ), ), const SizedBox(height: 40), // 跳转按钮 ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ResultScreen( height: _currentValue1, weight: _currentValue2, ), ), ); }, child: const Text('计算BMI'), ), ], ), ), ); } }
注意事项
- 确保你已经在
pubspec.yaml中添加了numberpicker依赖(比如numberpicker: ^2.1.2,可根据最新版本调整),并执行flutter pub get。 - 如果你的身高单位是米而非厘米,只需修改
_calculateBMI方法中的转换逻辑即可。 - 可以根据需求添加数值范围校验、结果分类(偏瘦/正常/偏胖/肥胖)等扩展功能。
内容的提问来源于stack exchange,提问作者Armin youuu
相关产品推荐
相关产品推荐

