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

Dart项目运行报错:类型'num?'无法赋值给类型'num'的变量问题求助

Fixing the Type Mismatch and Logic Error in Your Dart Birth Year Calculator

Let's break down and fix the two key issues in your code:

1. The Type Mismatch Error

num.tryParse() returns a nullable num? type—it gives null if the input can't be parsed as a valid number. You can't directly subtract this nullable value from DateTime.now().year (a non-nullable num), which is why you're seeing the type mismatch error.

2. The Incorrect Input Validation

Your code checks if n == "", but n is a num?—it will never be an empty string. When parsing fails, tryParse returns null, not "". This means your error message will never trigger, even for invalid inputs.

Corrected Code

Here's the fixed version with clear improvements:

import 'dart:io';

void main() {
  print("Enter your birth-year");
  // Capture raw input, default to empty string if input is null
  var input = stdin.readLineSync() ?? "";
  var birthYear = num.tryParse(input);

  // Check if parsing failed (birthYear is null)
  if (birthYear == null) {
    print("Bad Year");
    return; // Exit early to avoid running invalid age calculation
  }

  // Now birthYear is guaranteed non-null, so subtraction is safe
  var currentYear = DateTime.now().year;
  var age = currentYear - birthYear;
  print(" ==> You are $age year old!");
}

Key Improvements:

  • We first capture the raw input string separately, making the parsing logic clearer.
  • We validate by checking if birthYear is null (the actual result of a failed parse) instead of comparing to an empty string.
  • Added return after the error message to stop execution early—this prevents the code from trying to calculate age with an invalid value.
  • Renamed variables to be more descriptive (birthYear instead of n) for better readability.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:52:51