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

Issue

I am trying to add duration to a Timestamp in 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()))

It throws an error while calculating planned finish
error:

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

Solution

try duration!.toInt() .

you are making final double? duration nullable, do a null check before using.

Answered By – Yeasin Sheikh

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.