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
birthYearisnull(the actual result of a failed parse) instead of comparing to an empty string. - Added
returnafter 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 (
birthYearinstead ofn) for better readability.
内容的提问来源于stack exchange,提问作者Ahmed Farag
相关产品推荐
相关产品推荐

