You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart在if语句中定义boolean变量报Getter not found如何解决

问题原因
  • 变量作用域错误:isStudent、isSmart两个布尔变量都在if/else的块级作用域内声明,Dart中局部变量仅在声明它的代码块中有效,执行完if/else逻辑后两个变量就会被销毁,后续访问时就会触发Getter not found报错。
  • 语法错误:代码中else()的写法不符合Dart语法规范,else关键字后不需要附加空括号。
  • 额外冗余:导入了未使用的dart:math库,可直接删除。
修复方案

在if/else逻辑之前提前声明两个布尔变量,让作用域覆盖整个main函数范围,同时删除else后的多余括号即可。也可以直接用布尔表达式简化赋值逻辑,减少冗余代码。

修复后完整代码
import "dart:io";

String promptStudent(){
    print("are you a student?");
    String student = stdin.readLineSync()!;
    return student;
}

String promptSmart(){
    print("2+2=?");
    String smart = stdin.readLineSync()!;
    return smart;
}

void main() {
    String student = promptStudent();
    bool isStudent = student == "yes";

    String smart = promptSmart();
    bool isSmart = smart == "4";

    if (isSmart && isStudent) {
        print("he is a smart student");
    } else if (isSmart && !isStudent) {
        print("he is smart but not a student");
    } else if (!isSmart && isStudent) {
        print("he isnt smart but a student");
    } else {
        print("he is not smart and not a student");
    }
}

内容的提问来源于stack exchange,提问作者yagiz7v

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 06:24:03