美文网首页
flutter通过dio读取二进制数据,比如通过api接口读取图

flutter通过dio读取二进制数据,比如通过api接口读取图

作者: 王保全_1098 | 来源:发表于2018-12-03 00:51 被阅读0次
      // 通过attach的id属性读取图片,api接口返回图片的二进制数据
      getImage(MyAttach attach) async {
        Dio dio = Dio();
        SharedPreferences sp = await SharedPreferences.getInstance();
        dio.options.baseUrl = ServerUrl.base;
        dio.options.responseType = ResponseType.STREAM;
        Map<String, dynamic> headers = Map();
        headers["Authorization"] = sp.getString("token");
        dio.options.headers = headers;
        try {
          String url =
              "${ServerUrl.company}/${sp.getString("company_id")}/profile/${attach.id}?type=attach";
          print("url:$url");
          Response response = await dio.get(url);
          HttpClientResponse resp = response.data;
          final Uint8List bytes = await consolidateHttpClientResponseBytes(resp);
          print("服务器返回:${bytes.length}");
          attach.img = Image.memory(bytes);
          data.add(attach);
          setState(() {});
        } catch (e) {
          print("网络错误:" + e.toString());
        }
      }
    
      Future<Uint8List> consolidateHttpClientResponseBytes(
          HttpClientResponse response) {
        // response.contentLength is not trustworthy when GZIP is involved
        // or other cases where an intermediate transformer has been applied
        // to the stream.
        final Completer<Uint8List> completer = Completer<Uint8List>.sync();
        final List<List<int>> chunks = <List<int>>[];
        int contentLength = 0;
        response.listen((List<int> chunk) {
          chunks.add(chunk);
          contentLength += chunk.length;
        }, onDone: () {
          final Uint8List bytes = Uint8List(contentLength);
          int offset = 0;
          for (List<int> chunk in chunks) {
            bytes.setRange(offset, offset + chunk.length, chunk);
            offset += chunk.length;
          }
          completer.complete(bytes);
        }, onError: completer.completeError, cancelOnError: true);
    
        return completer.future;
      }
    

    相关文章

      网友评论

          本文标题:flutter通过dio读取二进制数据,比如通过api接口读取图

          本文链接:https://www.haomeiwen.com/subject/gflecqtx.html