skip to Main Content

enter image description here

I am facing this error that Null check operatorr

Null check operator used on a null value

The relevant error-causing widget was:
MaterialApp MaterialApp:file:///D:/Flutter%20Projects/bmi_calculator/lib/main.dart:12:12
When the exception was thrown, this was the stack:
#0 CalculatorBrain.getResult (package:bmi_calculator/bmi_calculator.dart:17:11)
#1 _InputPageState.build.. (package:bmi_calculator/input_page.dart:230:31)

This is my bmi_calculator.dart File

import 'dart:math';

class CalculatorBrain{
  CalculatorBrain({required this.height,required 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 && bmi!<25){
      return "Normal";
    }
    else{
      return "UnderWeight";
    }
  }

  String getInterpertation(){
    if(bmi!>=25){
      return "Your BMI is Height, you should do more exercises";
    }
    else if(bmi!>=18.5 && bmi!<25){
      return "Your BMI is Normal, you don't need any effort";
    }
    else{
      return "Your BMI is quite low, you should eat more";
    }
}
}

This is main.dart file

import 'package:flutter/material.dart';
import 'input_page.dart';

void main() {
  runApp(BMICalculator());
}
class BMICalculator extends StatelessWidget {
  const BMICalculator({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark().copyWith(
        colorScheme: ColorScheme.light(primary: Color(0xFF090C22),),
        scaffoldBackgroundColor: Color(0xFF0A0E21),
        appBarTheme: AppBarTheme(color: Color(0xFF090C22),centerTitle: true)
      ),
      home: InputPage(),
    );
  }
}


Please Help!

2

Answers


  1. Probably it’s because of this:

    double? bmi;
    
    ...
    
    if(bmi!>=25){
    

    You have a nullable double bmi and in the if statement, you are forcing it to be non null. A fix could be:

    double bmi = 0.0;
    
    ...
    
    if (bmi >= 25) {
    
    Login or Signup to reply.
  2. It is because you are initializing bmi as nullable and trying to use it in condition if(bmi!>=25) before it has any value.

    There are 2 possible solutions:

    double? bmi;
    
    if(bmi!=null && bmi!>=25){ ... }
    

    or

    double bmi = 0;
    
    if(bmi!>=25){ ... }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search