Flutter三元运算符异常:始终加载darkTheme问题求解
问题排查与解决步骤
1. 先确认weather?.day的实际值
在使用selectedTheme的位置添加打印语句,直接查看变量值:
print('weather 对象: $weather'); print('weather?.day 的值: ${weather?.day}'); print('条件判断结果: ${((weather?.day ?? 'Morning') == 'Morning')}');
从打印结果可直接定位问题:
- 如果
weather?.day是Night,说明Weather.fromJson里的is_day判断逻辑存在问题; - 如果
weather是null但条件仍不成立,需检查变量初始化时机是否导致兜底逻辑未生效。
2. 检查is_day字段的API返回值
在Weather.fromJson中添加打印,确认接口返回的is_day类型和值:
factory Weather.fromJson(Map<String, dynamic> json) { print('is_day 值: ${json['current']['is_day']}, 类型: ${json['current']['is_day'].runtimeType}'); return Weather( sunrise: json['daily']['sunrise'][0].split('T')[1], sunset: json['daily']['sunset'][0].split('T')[1], temp: json['current']['temperature_2m'].toString(), wind: json['current']['wind_speed_10m'].toString(), day: json['current']['is_day'] ? 'Morning' : 'Night', time: json['current']['time'].split('T')[1], ); }
多数天气API的is_day字段返回数字0/1而非布尔值,若直接用布尔判断:
- 数字0会被视为
false,返回Night; - 若API返回字符串
'0'/'1',非空字符串会被视为true,导致无论什么情况都返回Morning。
如果是数字类型,修改判断逻辑:
day: (json['current']['is_day'] == 1) ? 'Morning' : 'Night',
3. 确保selectedTheme能随weather更新
如果selectedTheme是final变量,它只会在初始化时计算一次,后续weather更新后不会自动重新计算。改成getter即可每次访问时重新判断:
final Weather? weather; ThemeData get selectedTheme => ((weather?.day ?? 'Morning') == 'Morning') ? lightTheme : darkTheme;
若使用状态管理(如Provider、Riverpod),需确保weather更新时能触发组件重建,让selectedTheme重新计算。
4. 验证空值兜底逻辑
若weather可能为null,可单独测试兜底逻辑是否生效:
// 模拟weather为null的情况 final Weather? testWeather = null; print('兜底测试结果: ${((testWeather?.day ?? 'Morning') == 'Morning')}'); // 应返回true
若此处返回false,需检查是否有其他代码修改了day的默认值。
内容的提问来源于stack exchange,提问作者Saumyal Baranwal
相关产品推荐
相关产品推荐

