flutter - 当我调用距离时,方法“toDouble”在 null 上被调用
问题描述
我从模型类中获取数据,当我从任何其他选项卡屏幕切换到此屏幕时,需要一两秒才能摆脱此错误:-
The method 'toDouble' was called on null.
Receiver: null
Tried calling: toDouble().
这是什么原因,我该如何摆脱这种情况?这是我显示它的地方,并评论了控制台中提到的链接在单击错误时将我带到的位置旁边的行:-
Padding(
padding: const EdgeInsets.all(15.0),
child: Card(
color: themeProvider.isDarkMode? black :white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text(
"Maximum distance",
style: TextStyle(
fontSize: 18,
color: mRed,
fontWeight: FontWeight.w500),
),
trailing: Text(
"$distance Km.",
style: TextStyle(fontSize: 16),
),
subtitle: Slider(
value: distance.toDouble(),/// Error takes me to this line.
inactiveColor: Colors.blueGrey,
min: 1.0,
max: 500,
activeColor: mRed,
onChanged: (val) {
changeValues
.addAll({'maximum_distance': val.round()});
setState(() {
distance = val.round();
});
}),
),
),
),
),
这是同一屏幕中的另一个错误:-
The getter 'start' was called on null.
Receiver: null
Tried calling: start
Padding(
padding: const EdgeInsets.all(15.0),
child: Card(
color: themeProvider.isDarkMode? black :white,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
title: Text(
"Age range",
style: TextStyle(
fontSize: 18,
color: mRed,
fontWeight: FontWeight.w500),
),
trailing: Text(
"${ageRange.start.round()}- // Error take me here ${ageRange.end.round()}",
style: TextStyle(fontSize: 16),
),
subtitle: RangeSlider(
inactiveColor: Colors.blueGrey,
values: ageRange,
min: 18.0,
max: 100.0,
divisions: 25,
activeColor: mRed,
labels: RangeLabels('${ageRange.start.round()}',
'${ageRange.end.round()}'),
onChanged: (val) {
changeValues.addAll({
'age_range': {
'min': '${val.start.truncate()}',
'max': '${val.end.truncate()}'
}
});
setState(() {
ageRange = val;
});
}),
),
),
),
),
解决方案
如果您distance
为 null,您将无法使用它的属性,例如distance.toDouble()
.
避免错误的一种方法是有条件地分配这样的值,
value: distance != null ? distance.toDouble() : 1.0,
现在,如果有的话distance
,null
您将1.0
改为分配默认值。
Text(ageRange != null ? "${ageRange.start.round()} - ${ageRange.end.round()}" : "invalid",
style: TextStyle(fontSize: 16),
),
推荐阅读
- postgresql - PostgreSQL 日期函数输出到法语
- python - 在python中将meshgrid点转换为邻接矩阵
- powerbi - Power BI中KPI在线趋势
- linux - 与作为变量传递给 awk 的正则表达式进行比较
- javascript - 基于用户代理重定向用户
- vba - VBA Excel - “.Find” 从上到下按 K 列的顺序搜索
- ios - 如何使用objective-c中的嵌套字典和动态键解析JSON响应?
- javascript - 如何在同一个 HTML 页面中制作所有 Plotly 图的离线绘图?
- validation - 使用组合键进行 rails 验证
- javascript - 如何使用 jquery/javascript 从 ontextchanged 事件中获取文本框值