首页 > 解决方案 > 如何修复在 null 上调用了方法“>=”。接收者:null 尝试调用:>=(25) in dart flutter

问题描述

伙计们,我正在尝试创建一个 BMI 计算器应用程序。一切正常,但在条件语句中传递数据时出现错误,如下所示。所以任何人都可以帮我解决这个问题,这对我很有帮助,谢谢:)

The following NoSuchMethodError was thrown building Builder(dirty):
The method '>=' was called on null.
Receiver: null
Tried calling: >=(25)

The relevant error-causing widget was: 
  MaterialApp file:///C:/Users/Prajesh/Desktop/Desktop/Flutter/bmi-calculator-flutter/lib/main.dart:8:12
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      CalculatorBrain.getResult (package:bmi_calculator/bmi_brain.dart:17:14)
#2      _InputPageState.build.<anonymous closure>.<anonymous closure> (package:bmi_calculator/inputPage.dart:225:25)
#3      MaterialPageRoute.buildContent (package:flutter/src/material/page.dart:54:55)
#4      MaterialRouteTransitionMixin.buildPage (package:flutter/src/material/page.dart:107:27)
...

所以基本上我创建了一个所有逻辑都发生的类,但是当我尝试将方法初始化为命名参数时,它会出错。

下面是我完成所有逻辑的代码

import 'dart:math';

class CalculatorBrain {
  CalculatorBrain({this.height, this.weight});

  final int height;
  final int weight;

  double _bmi;

  String calculateBMI() {
    _bmi = weight / pow(height / 100, 2);
    return _bmi.toStringAsFixed(1);
  }

  String getResult() {
    if (_bmi >= 25) {
      return 'Overweight';
    } else if (_bmi > 18.5) {
      return 'Normal';
    } else {
      return 'Underweight';
    }
  }

  String getInterpretation() {
    if (_bmi >= 25) {
      return 'You have a higher than normal body weight. Try to exercise more.';
    } else if (_bmi >= 18.5) {
      return 'You have a normal body weight. Good job!';
    } else {
      return 'You have a lower than normal body weight. You can eat a bit more.';
    }
  }
}

现在我在下面的代码中使用这个类,这是我的应用程序的首页

import 'package:bmi_calculator/result_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'custom_card_child.dart';
import 'reusable_container.dart';
import 'Constant.dart';
import 'bottom_button.dart';
import 'bmi_brain.dart';


enum Gender { male, female, }

class InputPage extends StatefulWidget {
  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {

  Gender selectedGender;
  int height = 180;
  int weight = 60;
  int age = 20;
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('BMI CALCULATOR'),
          centerTitle: true,
          elevation: 10.0,
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(child: Row(
            children: [
              Expanded(child: reusableContainer(
                  onPress: (){
                    setState(() {
                      selectedGender = Gender.male;
                    });
                  },
                  colour: selectedGender == Gender.male ? Kactiverang : Kinactiverang,
                cardChild: CustomCardChild(
                  icon: FontAwesomeIcons.mars,
                  text: 'MALE',
                ),
                  ),),
              Expanded(child: reusableContainer(
                  onPress: (){
                    setState(() {
                      selectedGender = Gender.female;
                    });
                  },
                  colour: selectedGender == Gender.female ? Kactiverang : Kinactiverang,
                  cardChild: CustomCardChild(
                    icon: FontAwesomeIcons.venus,
                    text: 'FEMALE',
                  ),
              ),),
          ],
        ),
            ),
            Expanded(child: reusableContainer(
                colour: Kactiverang,
                cardChild: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'HEIGHT',
                      style: KtextStyle,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: [
                        Text(
                          height.toString(),
                          style: KnumTextStyle,
                        ),
                        Text(
                          'cm'
                        )
                      ],
                    ),
                    SliderTheme(
                      data: SliderTheme.of(context).copyWith(
                        thumbShape: RoundSliderThumbShape(enabledThumbRadius: 15.0),
                        overlayShape: RoundSliderOverlayShape(overlayRadius: 30.0),
                        thumbColor: Color(0xFFEB1555),
                        activeTrackColor: Colors.white,
                        inactiveTrackColor: Color(0xFF8D8E98),
                        overlayColor: Color(0x29EB1555)
                      ),
                      child: Slider(
                          value: height.toDouble(),
                          min: 120.0,
                          max: 230.0,
                          //activeColor: Color(0xFFEB1555),
                          //inactiveColor: Color(0xFF8D8E98),
                          onChanged: (double newValue){
                            setState(() {
                              height = newValue.round();
                            });
                          },
                      ),
                    ),
                  ],
                ),
            ),),
            Expanded(child: Row(
            children: [
              Expanded(child: reusableContainer(
                  colour: Kactiverang,
                  cardChild: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'WEIGHT',
                        style: KtextStyle,
                      ),
                      Text(
                        weight.toString(),
                        style: KnumTextStyle,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          RoundIconButton(
                            onPress: (){
                              setState(() {
                                weight--;
                              });
                            },
                            icon: FontAwesomeIcons.minus,
                          ),
                          SizedBox(width: 10.0,),
                          RoundIconButton(
                            onPress: (){
                              setState(() {
                                weight++;
                              });
                            },
                            icon: FontAwesomeIcons.plus,
                          ),
                        ],
                      )
                    ],
                  ),
              )),
              Expanded(child: reusableContainer(
                  colour: Kactiverang,
                  cardChild: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'AGE',
                        style: KtextStyle,
                      ),
                      Text(
                        age.toString(),
                        style: KnumTextStyle,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          RoundIconButton(
                            onPress: (){
                              setState(() {
                                age--;
                              });
                            },
                            icon: FontAwesomeIcons.minus,
                          ),
                          SizedBox(width: 10.0,),
                          RoundIconButton(
                            onPress: (){
                              setState(() {
                                age++;
                              });

                            },
                            icon: FontAwesomeIcons.plus,
                          ),
                        ],
                      )
                    ],
                  ),
              )),
          ],
          ),
            ),
            Bottom_button(
              onPress: (){
                CalculatorBrain myBMI = CalculatorBrain(height: height, weight: weight);
                //CalculateBMI myBMI = CalculateBMI();
        Navigator.push(context,
            MaterialPageRoute(builder: (context) => ResultPage(
          result: myBMI.getResult(),
          remark: myBMI.getInterpretation(),
          bmiValue: myBMI.calculateBMI(),
        )));
      },
              button_titile: 'CALCULATE',
            ),
          ],
        ),
        ),
      );
  }
}


///////////////////////////////////////////////////////////////////////////////////////////////////////


class RoundIconButton extends StatelessWidget {
  RoundIconButton({@required this.onPress, @required this.icon});

  final Function onPress;
  final IconData icon;
  @override
  Widget build(BuildContext context) {
    return RawMaterialButton(
      onPressed: onPress,
      child: Icon(icon),
      elevation: 6.0,
      fillColor: Color(0xFF4C4F5E),
      shape: CircleBorder(),
      constraints: BoxConstraints.tightFor(width: 56.0, height: 56.0),


    );
  }
}

我想将这些数据传递到下面给出的下一页

import 'package:bmi_calculator/Constant.dart';
import 'package:bmi_calculator/reusable_container.dart';
import 'package:flutter/material.dart';
import 'bottom_button.dart';

class ResultPage extends StatelessWidget {

  final String result;
  final String bmiValue;
  final String remark;
  // ResultPage({@required this.bmiValue, @required this.remark, @required this.result});
  ResultPage({this.bmiValue, this.remark, this.result});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BMI CALCULATOR'),
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.all(15.0),
              alignment: Alignment.bottomLeft,
              child: Text('Your Result', style: KresultTextStyle,),
            ),
          ),
          Expanded(
            flex: 5,
            child: reusableContainer(
                colour: Kactiverang,
              cardChild: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(result.toUpperCase(), style: KnormalTextStyle,),
                  Text(bmiValue, style: KBMItextStyle,),
                  Text('all well',
                    style: KremarkTextStyle,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
          Bottom_button(onPress: (){Navigator.pop(context);}, button_titile: 'RE-CALCULATE'),
        ],
      ),
    );
  }
}

那么,谁能帮我解决这个问题,或者至少告诉我为什么我会收到这个错误?谢谢 :)

标签: androidflutterdart

解决方案


您在 calculateBMI() 之前调用 getResult(),其中您的 _bmi 为空,因此给出了异常。

您可以通过初始化值来解决它,但它不会修复结果页面中的值。

您可能想先计算 Bmi 并保存它然后传递它。像这样。

         onPress: (){
          CalculatorBrain myBMI = CalculatorBrain(height: height, weight: weight);
          final val = mBmi.calculateBMI();
          Navigator.push(context,
            MaterialPageRoute(builder: (context) => ResultPage(
          result: myBMI.getResult(),
          remark: myBMI.getInterpretation(),
          bmiValue: val,
        )));
      },

推荐阅读