方法'toInt'不能无条件调用,因为接收者在Dart中可以是'null'

The method 'toInt' can't be unconditionally invoked because the receiver can be 'null' in Dart

我正在尝试在 flutter 中为时间戳添加持续时间。

onPressed: () async {
                    final String? activity = _activity.text;
                    final double? slno = double.tryParse(_slno.text);
                    final double? duration = double.tryParse(_duration.text);
                    final double? dependent = double.tryParse(_dependent.text);

                    if (slno != null && activity != null) {
                      if (action == 'create') {
                        // Persist a new product to Firestore
                        var planneds = await getslno() ;
                        await _schedule.add({
                          "slno": slno,
                          "activity": activity,
                          "duration": duration,
                          "dependent": dependent,
                          "plannedstart":planneds,
                          "plannedfinish":planneds.toDate().add(Duration(days: duration.toInt()))

它在计算计划完成时抛出错误 错误:

The method 'toInt' can't be unconditionally invoked because the receiver can be 'null'.

试试 duration!.toInt() .

您正在使 final double? duration 可为空,请在使用前进行空检查。

检查值不能为空

Int.parse(value) ?? 0 以便如果传递空值,它 returns 零而不是空

Int.parse(value) == null ? 0 : int.parse(value)