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

  // 通过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 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 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 completer = Completer.sync();
    final List> chunks = >[];
    int contentLength = 0;
    response.listen((List chunk) {
      chunks.add(chunk);
      contentLength += chunk.length;
    }, onDone: () {
      final Uint8List bytes = Uint8List(contentLength);
      int offset = 0;
      for (List 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接口读取图片)