Flutter:如何处理 image/file 空路径的异常?

Flutter: How to handle exception for image/file empty path?

enter image description here我的 API 调用在所有字段都不为空时有效。

但是,我只想更新文本字段而不更新图像。当我触发更新按钮时。

它显示:未处理的异常:NoSuchMethodError:getter 'path' 被调用为 null。
接收者:空
尝试调用:path

这是我在 API_CODE_FOLDER

中的 POST
void updateData(
BuildContext context,
int id,
int userID,
String name,
String nric,
String dob,
File img,
String mobileNo,
int gender,
String nationality,
int race,
int religion,
String occupation,
String maritalStatus,
String deleteAt,
String createAt,
String updateAt,)async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final mimeTypeData =
    lookupMimeType(img.path, headerBytes: [0xFF, 0xD8]).split('/');
final file = await http.MultipartFile.fromPath('nric_front_copy', img.path,
    contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
refreshTokenApi(context);
print('UPDATE MOU');
accessToken = prefs.getString('access_token');
String myUrl = "$_url/personal_info";
var url = Uri.parse(myUrl);
var request = new http.MultipartRequest("POST", url);
request.headers['Accept'] = 'application/json';
request.headers['Authorization'] = 'Bearer $accessToken';
request.fields['id'] = id.toString();
request.fields['user_id'] = id.toString();
request.fields['name'] = name.trim();
request.fields['nric'] = nric.trim();
request.fields['date_of_birth'] = dob.trim();
request.files..add(file);
request.fields['mobile_no'] = mobileNo.trim();
request.fields['gender'] = gender.toString();
request.fields['nationality'] = nationality.trim();
request.fields['race_id'] = race.toString();
request.fields['religion_id'] = religion.toString();
request.fields['occupation'] = occupation.toString();
request.fields['marital_status'] = maritalStatus.toString();
request.fields['deleted_at'] = '';
request.fields['created_at'] = '';
request.fields['updated_at'] = '';
request.fields['_method'] = 'PATCH';
request.send().then((response){
  print(response.statusCode);
  print(response);
     if (response.statusCode == 200) {
    Navigator.pushReplacementNamed(context, '/Dashboard');
    print("updated!");
  } else if (response.statusCode != 201) {
    print(response.statusCode);
  }
});

}

这是我的更新

void updateButton() async {
print('TAPPED Update Button');
final SharedPreferences prefs = await SharedPreferences.getInstance();
// IF id & user_id is not empty then UPDATE.
if (prefs.getInt('id') != null || prefs.getInt('user_id') != null) {
    setState((){
    _gender = genderCon.text.isEmpty ? 1 : int.parse(genderCon.text);
    race = raceCon.text.isEmpty ? 2 : int.parse(raceCon.text);
    religion = religionCon.text.isEmpty ? 3 : int.parse(religionCon.text);
    _nric = icCon.text;
    _dob = dobCon.text;
    _name = nameCon.text;
    print(nameCon.text);
    print(nameCon.text.trim());
    callApi.updateData(
        context,
        id,
        userID,
        _name,
        _nric,
        _dob,
        _image,
        phoneCon.text,
        _gender,
        nationality,
        race,
        religion,
        occupation,
        maritalStatus,
        deleteAt,
        createAt,
        updateAt);
    print('UPDATE');
  });
}

}

这是我的获取图片功能

 void getImage() async {
var image = await ImagePicker.pickImage(
    source: ImageSource.gallery, imageQuality: 100);
setState(() {
  _image = image;
  Navigator.of(context);
});

}

    void updateData(
    BuildContext context,
    int id,
    int userID,
    String name,
    String nric,
    String dob,
    File img,
    String mobileNo,
    int gender,
    String nationality,
    int race,
    int religion,
    String occupation,
    String maritalStatus,
    String deleteAt,
    String createAt,
    String updateAt,)async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    refreshTokenApi(context);
    print('UPDATE MOU');
    accessToken = prefs.getString('access_token');
    String myUrl = "$_url/personal_info";
    var url = Uri.parse(myUrl);
    var request = new http.MultipartRequest("POST", url);

    if(img != null){
       final mimeTypeData =
            lookupMimeType(img.path, headerBytes: [0xFF, 0xD8]).split('/');
    final file = await http.MultipartFile.fromPath('nric_front_copy', img.path,

           contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
           request.files..add(file);

        }

    request.headers['Accept'] = 'application/json';
    request.headers['Authorization'] = 'Bearer $accessToken';
    request.fields['id'] = id.toString();
    request.fields['user_id'] = id.toString();
    request.fields['name'] = name.trim();
    request.fields['nric'] = nric.trim();
    request.fields['date_of_birth'] = dob.trim();
    request.fields['mobile_no'] = mobileNo.trim();
    request.fields['gender'] = gender.toString();
    request.fields['nationality'] = nationality.trim();
    request.fields['race_id'] = race.toString();
    request.fields['religion_id'] = religion.toString();
    request.fields['occupation'] = occupation.toString();
    request.fields['marital_status'] = maritalStatus.toString();
    request.fields['deleted_at'] = '';
    request.fields['created_at'] = '';
    request.fields['updated_at'] = '';
    request.fields['_method'] = 'PATCH';
    request.send().then((response){
      print(response.statusCode);
      print(response);
         if (response.statusCode == 200) {
        Navigator.pushReplacementNamed(context, '/Dashboard');
        print("updated!");
      } else if (response.statusCode != 201) {
        print(response.statusCode);
      }
    });

所以基本上它说 img 是空的,你正试图访问空对象上的方法 .path()。

因此,要阻止这种情况,您需要使用空检查来包装您的内容。在 dart 中有更好的方法可以做到这一点,例如 img?.path() 如果 img 不为空,它只会执行 path()

然而,让代码正常工作的最简单方法是将其包装在图像部分的 if 中。

试试这个:

void updateData(
BuildContext context,
int id,
int userID,
String name,
String nric,
String dob,
File img,
String mobileNo,
int gender,
String nationality,
int race,
int religion,
String occupation,
String maritalStatus,
String deleteAt,
String createAt,
String updateAt,)async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
refreshTokenApi(context);
print('UPDATE MOU');
accessToken = prefs.getString('access_token');
String myUrl = "$_url/personal_info";
var url = Uri.parse(myUrl);
var request = new http.MultipartRequest("POST", url);
request.headers['Accept'] = 'application/json';
request.headers['Authorization'] = 'Bearer $accessToken';
request.fields['id'] = id.toString();
request.fields['user_id'] = id.toString();
request.fields['name'] = name.trim();
request.fields['nric'] = nric.trim();
request.fields['date_of_birth'] = dob.trim();
if(img != null)
{
    var mimeTypeData =
    lookupMimeType(img.path, headerBytes: [0xFF, 0xD8]).split('/');
    var file = await http.MultipartFile.fromPath('nric_front_copy', img.path,
    contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
    request.files..add(file);
}
request.fields['mobile_no'] = mobileNo.trim();
request.fields['gender'] = gender.toString();
request.fields['nationality'] = nationality.trim();
request.fields['race_id'] = race.toString();
request.fields['religion_id'] = religion.toString();
request.fields['occupation'] = occupation.toString();
request.fields['marital_status'] = maritalStatus.toString();
request.fields['deleted_at'] = '';
request.fields['created_at'] = '';
request.fields['updated_at'] = '';
request.fields['_method'] = 'PATCH';
request.send().then((response){
  print(response.statusCode);
  print(response);
     if (response.statusCode == 200) {
    Navigator.pushReplacementNamed(context, '/Dashboard');
    print("updated!");
  } else if (response.statusCode != 201) {
    print(response.statusCode);
  }
});