简体   繁体   中英

Unhandled Exception: Converting object to an encodable object failed: Instance of 'XFile'

#this is my class where i called api

 static Future<void> postHomework(String classId,String sectionId,String homeWorkTitle,String link,String homeworkDetail, List<XFile> homeworkImage,String submissionDate,BuildContext context) async{
    String userData;
    String token;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userData = prefs.getString("userData");
    if(userData!=null){
      token = json.decode(userData)['token'];
    }else{
     return;
    }
    const url = "my api goes here";
  
    Map<String,dynamic> jsonData = {
      "classid":classId,
      "sectionid":sectionId,
      "title":homeWorkTitle,
      "content":homeworkDetail,
      "submission_date":submissionDate,
      "filename":homeworkImage,
      "link":link
    };
    print(homeworkImage);
    try{
      EasyLoading.show(status: "posting homework");
      final jsonString = json.encode(jsonData);
      final response = await http.post(Uri.parse(url),body: jsonString,headers: {'Content-Type': 'multipart/form-data','Authorization': 'Bearer $token',},);
      final responseData = json.decode(response.body);
      if(response.statusCode==200){
        print(responseData);
        Navigator.of(context).pushNamed("Homework-section-subject-list");
        EasyLoading.dismiss();
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
          content: Padding(
            padding: EdgeInsets.only(right: 100.w),
            child: Text(
              'Homework posted successfully',
              maxLines: 2,
              style: TextStyle(fontSize: 14.sp),),
          ),
          duration: const Duration(seconds: 2),
          backgroundColor: Colors.grey.shade700,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.r)
          ),
        ));
      }
    }catch(e){
      rethrow;
    }
  }

#this way i picked image from gallery and store it in List imageFileList = [];

 final ImagePicker imagePicker = ImagePicker();
  List<XFile> imageFileList = [];
  void selectImages() async {
    final XFile selectedImages = await imagePicker.pickImage(source: ImageSource.gallery);
    if (selectedImages.path.isNotEmpty) {
      imageFileList.add(selectedImages);
    }
    print("Image List Length:" + imageFileList.length.toString());
    setState((){});
  }

#This is my postHomework controller

class HomeworkPostController extends GetxController{
  var isLoading = true.obs;

  Future<void> postHomework(String classId,String sectionId,String homeWorkTitle,String link,String homeworkDetail, List<XFile> homeworkImage,String submissionDate,BuildContext context) async{
    try{
      isLoading(true);
      EasyLoading.show(status: "posting homework");
      return await Services.postHomework(classId, sectionId, homeWorkTitle, link, homeworkDetail, homeworkImage, submissionDate, context);
    }finally{
      isLoading(false);
      EasyLoading.dismiss();
    }
  }
}

#i passed data on botton press

  onPressed: (){
                          if(_form.currentState.validate()) {
                            hP.postHomework(
                                classId,
                                sectionId,
                                titleController.text,
                                linkController.text,
                                detailController.text,
                                imageFileList,
                                submissionDateController.text,
                                context);
                          }
}

everything is fine all data is being passed accept for the image part need help I am getting error saying E/flutter ( 7064): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'XFile'

You can't convert image to json by json.encode . you passed List<XFile> homeworkImage to "filename" in jsonData . it's not working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM