Search code examples
mongodbfile-uploadmultipartform-dataform-data

Flutter - Unhandled Exception: NoSuchMethodError: The getter 'filename' was called on null


I am still learning flutter and have been facing problems in my project like the error stated in the title. I want to upload files in flutter using dio and formData. The img[] is the variable from the database in mongodb and I am having an error whenever the user passes null image. (Because we do not require the user to send an image.)

Here's my code.

 upload2(List<File> babyList) async {

    var formData = FormData.fromMap({
      "userId": _id,
      "babyname": _baby,
    });

    if(_babyList.length != 0){
      for (int i = 0; i < _babyList.length; i++) {
        var fileName = babyList[i].path.split('/').last;
        formData.files.addAll([
          MapEntry(
              "babyimage[]",
              await MultipartFile.fromFile(babyList[i].path,
                  filename: fileName,
                  contentType: new MediaType(lookupMimeType(fileName).split('/')[0], lookupMimeType(fileName).split('/')[1],
                  ))),
        ]);
      }
    } else {
      formData.files.addAll([ MapEntry("babyimage[]", null)]);
    }

    // sending the formdata to the database
    AuthService().requestorRegister(formData).then((val) async {
      print('Form Submitted Successfully');
      _confirmationDialog(context);
    });

  }

Solution

  • Okay, I have tried not to add babyimage[] in the formdata, I have also tried to put empty array, null and babyList as value. The thing is they work and the only problem in my case is the server. The server wasn't updated. So sometimes we gotta check the server too. lol

    PS. I removed the else in the code since it is empty.