zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Flutter Dio网络请求异常处理

flutter网络异常 处理 请求
2023-09-14 09:04:29 时间

参考

  try {
    Response r = await dio.get("https://www.instagram.com");
    print(r.headers);
  }on DioError catch(e){
     print(e);
     print(e.response.statusCode);
  }

我的代码操作如下

  void _submitData () async {
    try {
      //处理图片
      List<MultipartFile> imageList = new List<MultipartFile>();
      for (Asset asset in images) {
        //将图片转为二进制数据
        ByteData byteData = await asset.getByteData();
        List<int> imageData = byteData.buffer.asUint8List();
        MultipartFile multipartFile = new MultipartFile.fromBytes(
          imageData,
          //这个字段要有,否则后端接收为null
          filename: 'load_image',
          //请求contentType,设置一下,不设置的话默认的是application/octet/stream,后台可以接收到数据,但上传后是.octet-stream文件
          contentType: MediaType("image", "jpg"),
        );
        imageList.add(multipartFile);
      }

      FormData formData = FormData.fromMap({
        //后端要用multipartFiles接收参数,否则为null
        "photos" : imageList,
        "text" : _momentController.text
      });
      // var res = await Dio().post("你的URL", data: formData);
      //后面随意发挥
      var apiUrl = "http://47.242.63.216:9527/v1/moment";
      SharedPreferences prefs = await SharedPreferences.getInstance();
      var tokens = prefs.getString("token");

      // 后端接口的其他参数
      Map<String, dynamic> params = Map();

      //网络请求添加token请求头
      Response result = await Dio().post(apiUrl,
          data: formData, options: Options(headers: {"x-token": tokens}));
      debugPrint("${result}");
      // 使用 dio 上传图片
      // var response = await dio.post(url, data: formData, queryParameters: params);
      //
      // do something with response...
      //json解析
      Map<String, dynamic> authCode = json.decode(result.toString());
      var mes = PublishMomentData.fromJson(authCode);
      if (mes.code == 200) {
        Fluttertoast.showToast(
            msg: "发布成功",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 10,
            backgroundColor: Colors.white,
            textColor: Colors.black,
            fontSize: 16.0);
        //返回动态界面
        Navigator.pop(context);
        Navigator.pop(context);
      } else {
        Fluttertoast.showToast(
            msg: "发布失败",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 10,
            backgroundColor: Colors.white,
            textColor: Colors.black,
            fontSize: 16.0);
      }
    }on DioError catch(e){
      Fluttertoast.showToast(
          msg: "${e}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 10,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0);
      print(e);
      print(e.response.statusCode);
    }
  }