Unhandled Exception: NoSuchMethodError: Class 'String' has no instance getter 'path'

Issue

I have tried to upload multiple images through multi_image_picker depedency and using multipart request,
where I upload images on first screen and get them on another screen and tried to post them through API,
instead gets an error in LogCat as below:

I/flutter ( 6514): Electronics images --
I/flutter ( 6514): [/data/user/0/com.etroc.etroc/cache/IMG_1611380223006.png, /data/user/0/com.etroc.etroc/cache/IMG_1611380223017.png, /data/user/0/com.etroc.etroc/cache/IMG_1611380223027.png]
I/flutter ( 6514): /data/user/0/com.etroc.etroc/cache/IMG_1611380223006.png
E/flutter ( 6514): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance getter 'path'.
E/flutter ( 6514): Receiver: "/data/user/0/com.etroc.etroc/cache/IMG_1611380223006.png"
E/flutter ( 6514): Tried calling: path
E/flutter ( 6514): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 6514): #1      _PaymentforAdsState.submitpayment (package:etroc/Screens/paymentForPostAds.dart:191:35)
E/flutter ( 6514): #2      _PaymentforAdsState.build.<anonymous closure> (package:etroc/Screens/paymentForPostAds.dart:1024:21)
E/flutter ( 6514): #3      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
E/flutter ( 6514): #4      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1111:38)
E/flutter ( 6514): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:183:24)
E/flutter ( 6514): #6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:598:11)
E/flutter ( 6514): #7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:287:5)
E/flutter ( 6514): #8      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:259:7)
E/flutter ( 6514): #9      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:157:27)
E/flutter ( 6514): #10     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:362:20)
E/flutter ( 6514): #11     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:338:22)
E/flutter ( 6514): #12     RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:267:11)
E/flutter ( 6514): #13     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:295:7)
E/flutter ( 6514): #14     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:240:7)
E/flutter ( 6514): #15     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:213:7)
E/flutter ( 6514): #16     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter ( 6514): #17     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter ( 6514): #18     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter ( 6514): #19     _invoke1 (dart:ui/hooks.dart:265:10)
E/flutter ( 6514): #20     _dispatchPointerDataPacket (dart:ui/hooks.dart:174:5)
E/flutter ( 6514): 


This is my API post code-


submitpayment(BuildContext context,List files)async{
    print("submitpayment");
    print(widget.categoryname);
    if(widget.categoryname.toString()=='Electronics'){
      print("Electronics images --");
      print(files);

        var uri = Uri.parse(
            "api_url_link");
        var request = new http.MultipartRequest("POST", uri);
        for (var file in files) {
          print(file);
          String  fileName = file.path.split('/').last;
          var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
          var length = await file.length();
          var multipartFileSign =
          new http.MultipartFile('resplist', stream, length, filename: fileName);
          request.files.add(multipartFileSign);
        }
        Map<String, String> headers = {
          "Accept": "application/json",
        };
        request.headers.addAll(headers);
        request.fields['adTitle'] = widget.adtitle;
        request.fields['yearofPurchase'] = widget.yearofpur;
        request.fields['processor'] = widget.processor;
        request.fields['frontCamera'] = widget.frontcamera;
        request.fields['backCamera'] = widget.backcamera;
        request.fields['sellingPrice'] = widget.sellingprice;
        request.fields['isNegotiate'] = widget.negotiate;
        request.fields['description'] = widget.description;
        request.fields['color'] = widget.color;
        request.fields['productId'] = widget.prodname;
        request.fields['brandId'] = widget.brandid;
        request.fields['productConditionId'] = widget.prodcondition;
        request.fields['customerId'] = widget.customer;
        request.fields['mobileNumber'] = widget.cotact;
        request.fields['inActivePeriod'] = _inActivePeriod;
        request.fields['adsTypeId'] = _adsTypeId;
        request.fields['adsTypeName'] = _adsTypeName;
        request.fields['localityId'] = widget.locality;
        request.fields['subCategoryId'] = widget.sub_catId;
        request.fields['categoryId'] = widget.categoryid;
        var response = await request.send();
        print(response.statusCode);
        response.stream.transform(utf8.decoder).listen((value) {
         // Navigator.pop(context);
          if (response.statusCode == 200) {
            var res = jsonDecode(value);
            print("payment done - "+res);
          } else {
            print("error in submit");
          }
        });
}
}

This is my code where I upload multiple images (First Screeen)-

 String fileName;
  List<Asset> images= List<Asset>();
 Future<void> pickImages() async {
    setState(() {
      images = null;
    });
    List resultList;
    String error;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 4,
      );
    } on PlatformException catch (e) {
      error = e.message;
    }
    if (!mounted) return;
    setState(() {
      images = resultList;
      if (error == null) _error = 'No Error Dectected';
    });

  }
  Future<File> getImageFileFromAsset(String path) async {
    final file = File(path);
    return file;
  }

  productInfo() async {
    files.clear();
    for (int i = 0; i < images.length; i++) {
      var path2 = await FlutterAbsolutePath.getAbsolutePath(images[i].identifier);
      //var path = await images[i].filePath;
      print(path2);
//      var file = await getImageFileFromAsset(path2);
//      print(file);
      var file = await getImageFileFromAsset(path2);

//      var base64Image = base64Encode(file.readAsBytesSync());
//      print(base64Image);
//      files.add(base64Image);
//      var data = {
//      //“files”: files,
//    };
      print(file);
      _img.add(path2);
      print(_img);
    }
 return showDialog(
          context: context,
          builder: (BuildContext context) {
            return ProductInfo(
              custid:widget.user,
              contact:widget.mobid,
              catId:widget.category_id,
              sub_catId: widget.sub_CategoryId,
              sub_catname: widget.sub_CategoryName,
              imgList: _img,
              categoryName: widget.category_Name,
            );
          });
}
  Widget setupAlertDialoadContainer() {
    return Container(
      width: 300.0,
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text("You can add upto 4 Images",
              style: TextStyle(color: Colors.black,fontWeight: FontWeight.w400, fontSize: 12),
              textAlign: TextAlign.center,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Column(children: [
                  Image.asset("assets/cameraicon_red.png", height: 80,width: 80,),
                  SizedBox(height: 10,),
                  RaisedButton(
                    //onPressed:chooseFile ,
                    onPressed:pickImages ,
                    child: Text('UPLOAD',style: TextStyle(fontSize: 14, color: Colors.black),),
                  ),
                ],),
                SizedBox(width: 5,),
                images == null
                    ?  Container()
                    :  SizedBox(
                  height: 100.0,
                  width: 180,
                  child: new ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemBuilder: (BuildContext context, int index) =>
                    new Padding(
                        padding: const EdgeInsets.all(5.0),

                        child : AssetThumb(
                          asset: images[index],
                          height: 200,
                          width: 200,
                        )
                    ),
                    itemCount: images.length,
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 25,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                GestureDetector(onTap: () { productInfo();
                   },
                  child: Container(
                    alignment: Alignment.center, width: 80,
                    padding: EdgeInsets.symmetric(vertical: 5),
                    decoration: BoxDecoration(color: Colors.white, border: Border.all(color: primary)),
                    child: Text("NEXT", style: TextStyle(fontSize: 14, color: primary),),
                  ),
                ),
                GestureDetector(onTap: () {Navigator.pop(context);},
                  child: Container(
                    alignment: Alignment.center,
                    width: 80,
                    padding: EdgeInsets.symmetric(vertical: 5),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: primary)
                    ),
                    child: Text("CANCEL", style: TextStyle(fontSize: 14, color: primary),),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Dialog(
      elevation: 0, insetPadding: EdgeInsets.all(10),
      backgroundColor: Colors.transparent,
      child: contentBox(context),
    );
  }
  contentBox(context){
    return AlertDialog(
      backgroundColor: Colors.white,
      contentPadding: EdgeInsets.only(top: 10.0),
      content: setupAlertDialoadContainer(),
    );
  }
}

THis is my UI code where I post images (second Screen)-

Widget build(BuildContext context) {
    height = MediaQuery.of(context).size.height;
    width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primary,
        automaticallyImplyLeading: true,
        centerTitle: true,
        elevation: 0.0,
      ),
      body:SingleChildScrollView(
        child: Column(
          children: [
            Container(
              decoration: BoxDecoration(color: Colors.grey[200]),
              height: height/1.5,
              child: GridView.builder(
                shrinkWrap: true,
                itemCount:_list.length==null?2:_list.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    childAspectRatio: MediaQuery.of(context).size.width /
                        MediaQuery.of(context).size.height /
                        0.7,
                    crossAxisCount: 2,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10),
                padding: EdgeInsets.only(left: 15, right: 15, bottom: 10, top: 10),
                itemBuilder: (context, index) {
                  return InkWell(
                    onTap: () {
                    },
                    child: Container(
                      padding: const EdgeInsets.all(8.0),
                      decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border.all(color: primary),
                          borderRadius: BorderRadius.all(Radius.circular(15))),
                      child: Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            Container(
                              width: 180,
                              height: 30,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(8.0),
                                border: Border.all(color: primary),
                              ),
                              child: Center(
                                child: Text(_list[index].adsTypeName==null?"Free":_list[index].adsTypeName,
                                  style: TextStyle(
                                      fontWeight: FontWeight.w500,
                                      fontSize: 12),
                                ),
                              ),
                            ),
                            SizedBox(height: 20),
                            Flexible(
                              child: Text(_list[index].price==null?"0":_list[index].price,
                                style: TextStyle(
                                    fontWeight: FontWeight.w500,
                                    fontSize: 16),
                              ),
                            ),
                            SizedBox(height: 20),
                            Flexible(
                              child: Text(_list[index].activePeriod==null
                                  ? 0 :_list[index].activePeriod.toString(),
                                maxLines: 2,
                                style: TextStyle(
                                    fontWeight: FontWeight.w500,
                                    fontSize: 16),
                              ),
                            ),
                            SizedBox(height: 20),
                            Radio(
                              value: _list[index].adsTypeName,
                              groupValue: checkbox,
                              onChanged: ( value){
                                setState(() {
                                  _inActivePeriod=_list[index].inActivePeriod;
                                  _adsTypeId=_list[index].adsTypeId;
                                  _adsTypeName=_list[index].adsTypeName;
                                  checkbox=value;
                                });
                              },
                            )
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            Align(
              alignment: Alignment.center,
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: 25,vertical: 25),
                alignment: Alignment.center,
                //width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.symmetric(vertical: 25,horizontal: 12),

                child: RaisedButton(
                  color: Colors.red,
                  onPressed: (){
                    submitpayment(context, widget.imgList);
                  },
                  child: Text('SUBMIT',style: TextStyle(
                      fontSize: 14,
                      color: Colors.white)
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Can someone help me? Because I was dizzy to find a solution to this error 🙂

Solution

You file variable is a String, not a File. Check files collections creation and pass into submitpayment list with type definition (List<File>) for check this issue at compile time.

Answered By – fartem

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.