【问题标题】:error: Non-nullable instance field 'result' must be initialized错误:必须初始化不可为空的实例字段“结果”
【发布时间】:2021-07-13 00:27:00
【问题描述】:

我是一个 Flutter 初学者开发者,我目前正在使用 Flutter 和 Dart 开发一个 BMI 计算器应用程序。实际上,在我的代码中,我面临以下错误。

  • error: Non-nullable instance field 'result' must be initialized at [bmi_app] lib\calresult.dart:16)
  • error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type. (body_might_complete_normally at [bmi_app] lib\calresult.dart:16)

这是我的 main.dart 文件:

import 'package:bmi_app/calresult.dart';
import 'package:bmi_app/resultscreen.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

enum Gender {
  male,
  female,
}

void main() {
  runApp(MaterialApp(
      theme: ThemeData(
        primaryColor: Color(0xFF24232F),
        accentColor: Color(0XFF1F1E29),
        scaffoldBackgroundColor: Color(0xFF2F2E3A),
      ),
      debugShowCheckedModeBanner: false,
      home: InputScreen()
    )
  );
}

class InputScreen extends StatefulWidget {
  const InputScreen({Key? key}) : super(key: key);

  @override
  _InputScreenState createState() => _InputScreenState();
}

class _InputScreenState extends State<InputScreen> {
  Color inactiveColor = Color(0xFF24232F);
  Color activeColor = Colors.blueGrey;
  Gender selectedGender = Gender.values.single;

  int height = 100;
  int weight = 50;
  int age = 15;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Center(
          child: Text(
              "BMI Calculator"
          ),
        ),
      ),
      body: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        selectedGender = Gender.male;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(10.0),
                      margin: EdgeInsets.all(10.0),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12.0),
                          color: selectedGender == Gender.male
                              ? activeColor
                              : inactiveColor
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Icon(
                            FontAwesomeIcons.male,
                            color: Colors.white,
                            size: 45.0,
                          ),
                          SizedBox(
                            height: 10.0,
                          ),
                          Text(
                            "Male",
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 20.0,
                              fontWeight: FontWeight.w500,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        selectedGender = Gender.female;
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(10.0),
                      margin: EdgeInsets.all(10.0),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.0),
                          color: selectedGender == Gender.female
                              ? activeColor
                              : inactiveColor
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Icon(
                            FontAwesomeIcons.female,
                            color: Colors.white,
                            size: 45.0,
                          ),
                          SizedBox(
                            height: 10.0,
                          ),
                          Text(
                            "Female",
                            style: TextStyle(
                              color: Colors.grey,
                              fontSize: 20.0,
                              fontWeight: FontWeight.w500,
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
          SizedBox(
            height: 10.0,
          ),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.0),
                  color: inactiveColor
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    "HEIGHT",
                    style: TextStyle(
                      fontSize: 16.0,
                      color: Colors.white,
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.baseline,
                    textBaseline: TextBaseline.alphabetic,
                    children: [
                      Text(
                          height.toString(),
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 35.0,
                            fontWeight: FontWeight.bold,
                          )
                      ),
                      Text(
                        "cm",
                        style: TextStyle(
                          fontSize: 18.0,
                          color: Colors.white,
                        ),
                      )
                    ],
                  ),
                  SliderTheme(data: SliderTheme.of(context).copyWith(
                    activeTrackColor: Colors.white,
                    overlayColor: Color(0x291DE9B6),
                    inactiveTrackColor: Colors.grey,
                    thumbShape: RoundSliderThumbShape(
                        enabledThumbRadius: 16.0
                    ),
                    overlayShape: RoundSliderOverlayShape(
                        overlayRadius: 30.0
                    ),
                    thumbColor: Color(0xFF1DE9B6),
                  ),
                      child: Slider(
                        value: height.toDouble(),
                        min: 50.0,
                        max: 300.0,
                        onChanged: (double v){
                          setState(() {
                            height = v.round();
                          });
                        },
                      )
                  )
                ],
              ),
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(
                        bottom: 10.0
                    ),
                    margin: EdgeInsets.only(
                        top: 10.0
                    ),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.0),
                        color: inactiveColor
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          "Weight",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            )
                        ),
                        SizedBox(
                          height: 8.0,
                        ),
                        Text(
                          weight.toString(),
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            )
                        ),
                        SizedBox(
                          height: 8.0,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            CircleAvatar(
                              backgroundColor: Colors.blueGrey,
                              child: IconButton(
                                icon: Icon(
                                  Icons.add,
                                  color: Colors.white,
                                ),
                                onPressed: (){
                                  setState(() {
                                    weight++;
                                  });
                                },
                              ),
                            ),
                            SizedBox(
                              width: 10.0
                            ),
                              CircleAvatar(
                                backgroundColor: Colors.blueGrey,
                                child: IconButton(
                                  icon: Icon(
                                    Icons.remove,
                                    color: Colors.white,
                                  ),
                                  onPressed: (){
                                    setState(() {
                                      if(weight>10){
                                        weight--;
                                      }
                                    }
                                    );
                                  },
                                ),
                              ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(
                        bottom: 10.0
                    ),
                    margin: EdgeInsets.only(
                        top: 10.0
                    ),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.0),
                        color: selectedGender == Gender.female
                            ? activeColor
                            : inactiveColor
                    ),
                    child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                        Text(
                        "Age",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            )
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    Text(
                        age.toString(),
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        )
                    ),
                    SizedBox(
                      height: 8.0,
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                      CircleAvatar(
                      backgroundColor: Colors.blueGrey,
                      child: IconButton(
                        icon: Icon(
                          Icons.add,
                          color: Colors.white,
                        ),
                        onPressed: (){
                          setState(() {
                            age++;
                          });
                        },
                      ),
                    ),
                    SizedBox(
                        width: 10.0
                    ),
                    CircleAvatar(
                      backgroundColor: Colors.blueGrey,
                      child: IconButton(
                        icon: Icon(
                          Icons.remove,
                          color: Colors.white,
                        ),
                        onPressed: (){
                          setState(() {
                            if(age>5){
                              age--;
                            }
                          }
                          );
                        },
                      ),
                    ),
              ],
            )
        ],
      ),
    ),
                ),
              ],
            ),
          ),
          GestureDetector(
            child: Container(
              padding: EdgeInsets.only(
                bottom: 10.0
              ),
              margin: EdgeInsets.only(
                top: 10.0
              ),
              width: double.infinity,
              height: 80.0,
              color: Color(0xFF1DE9B6),
              child: Center(
                child: Text(
                  "Calculate BMI",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 25.0,
                      fontWeight: FontWeight.bold,
                    )
                ),
              ),
            ),
            onTap: (){
              navigateToResultScreen(12.0);
            },
          )
        ],
      ),
    );
  }

  void navigateToResultScreen(double result){
    CalculateResult obj = CalculateResult(weight, height);
    Navigator.push(context, MaterialPageRoute(builder: (context) => ResultScreen(obj.calculateResult(),obj.msg, obj.getDescription())));
  }
}

除此之外还有另外两个文件:

  • resultscreen.dart:

      import 'package:flutter/material.dart';
    
      class ResultScreen extends StatefulWidget {
        String result;
        String msg;
        String des;
        ResultScreen(this.result, this.msg, this.des);
    
        @override
        _ResultScreenState createState() => _ResultScreenState();
      }
    
      class _ResultScreenState extends State<ResultScreen> {
        @override
        Widget build(BuildContext context) {
          return Scaffold(
            backgroundColor: Color(0xFF2F2E3A),
            appBar: AppBar(
              title: Text("BMI Results"),
            ),
            body: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(
                  flex: 1,
                  child: Text("Your Results",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 25.0,
                        fontWeight: FontWeight.bold,
                      )
                  ),
                ),
                Expanded(
                  flex: 5,
                  child: Container(
                    padding: EdgeInsets.only(
                        bottom: 10.0
                    ),
                    margin: EdgeInsets.only(
                        top: 10.0
                    ),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12.0),
                        color: Color(0xFF2F2E3A)
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          widget.result,
                          style: TextStyle(
                            color: Colors.green,
                            fontSize: 26.0,
                          ),
                        ),
                        Text(
                          widget.msg,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.green,
                            fontSize: 26.0,
                          ),
                        ),
                        Text(
                          widget.des,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 26.0,
                          ),
                        ),
                        Expanded(
                          child: GestureDetector(
                            onTap: (){
                              Navigator.pop(context);
                            },
                            child: Container(
                              padding: EdgeInsets.all(10.0),
                              margin: EdgeInsets.only(
                                bottom: 10.0
                              ),
                              alignment: Alignment.center,
                              color: Color(0xFF1DE9B6),
                              child: Text(
                                "Recalculate...",
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 25.0,
                                    fontWeight: FontWeight.bold,
                                  )
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        }
      }
    
    • 还有 calresult.dart:

导入“飞镖:数学”;

class CalculateResult{
  CalculateResult(this.weight, this.height);
  final int height;
  final int weight;
  double result;
  String msg = "Normal";

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

  String getDescription(){
    if(result > 25){
      msg = "Over weight";
      return "You have a higher weight than normal. Try to lose somme through any activity you like!";
    }
    else if(result > 18.5){
      msg = "Normal";
      return "You have a normal weight. Keep it!";
    }
    else if(result < 18.5){
      msg = "Under Weight";
      return "Your weight is less than normal weight. You need to get some. Make sure to have a correct and balanced diet. ";
    }
  }
}

希望从社区中获得一些有用的提示来解决这些错误。谢谢!

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的calresult.dart 文件有两个问题。

    首先,有一个可以为 null 的实例,称为 result。所以,我们需要初始化它,或者我们可以使用late keyword 作为结果变量。通过声明一个不可为空的 late 变量,我们保证它在运行时是非空的,Dart 帮助我们提供了一些编译时保证。

    下一个问题是,您需要在 getDescription() 方法中返回 String。因为它的返回类型是String。

    calresult.dart 文件(固定一个)-

    class CalculateResult{
      
      final int height;
      final int weight;
      late double result;
      String msg = "Normal";
      
      CalculateResult(this.weight, this.height);
    
      String calculateResult(){
        result = weight / pow(height/100, 2);
        return result.toStringAsFixed(1);
      }
    
      String getDescription(){
        if(result > 25){
          msg = "Over weight";
          return "You have a higher weight than normal. Try to lose somme through any activity you like!";
        }
        else if(result > 18.5){
          msg = "Normal";
          return "You have a normal weight. Keep it!";
        }
        else if(result < 18.5){
          msg = "Under Weight";
          return "Your weight is less than normal weight. You need to get some. Make sure to have a correct and balanced diet. ";
        }
        
        return "need to return string";
      }
    }
    

    希望这能解决您的问题!

    【讨论】:

    • 非常感谢@Yohan,这确实解决了发生的错误。
    【解决方案2】:

    String getDescription() 表示它必须返回String,但有一个案例返回null

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2021-07-06
      • 1970-01-01
      • 2022-08-18
      • 2021-09-14
      • 2021-09-24
      • 2021-10-11
      • 2021-08-27
      • 2022-01-25
      相关资源
      最近更新 更多