Flutter: HTTP Get возвращает экземпляр будущего вместо Image приводит к исключению - PullRequest
0 голосов
/ 03 марта 2020

Моя цель: Скачать изображение с URL-адреса, сохранить его в каталоге, а затем с помощью пакета carousel_slider.dart создать слайдер. Все работает нормально, после того как for l oop выполнено, я получаю ошибку во время выполнения, говорящую об исключении: Не удалось создать экземпляр кода изображения c. После использования оператора print я получаю экземпляр 'response'.

На основании этого сообщения об ошибке я могу предположить, что мой код пытается декодировать изображение перед его загрузкой.

Консоль:

Performing hot restart...
Syncing files to device sdk google atv x86...
Restarted application in 3,046ms.
I/flutter ( 3664): ::Data connection is available.
I/flutter ( 3664): ::Mosquitto client connecting....
I/flutter ( 3664): ::Subscription confirmed -> topic -> topic/registered
I/flutter ( 3664): ::Change notification:: topic -> <topic/registered>, payload ->  <1> 
I/flutter ( 3664): Payload: 1
I/flutter ( 3664): ::Subscription confirmed -> topic -> topic/control_instruction
I/flutter ( 3664): Instance of 'Response'
I/flutter ( 3664): Instance of 'Response'
I/flutter ( 3664): Instance of 'Response'
I/flutter ( 3664): [/data/user/0/com.stellar.dnb/app_flutter/Notice/1583231584.jpg, /data/user/0/com.stellar.dnb/app_flutter/Notice/1583237477.jpg, /data/user/0/com.stellar.dnb/app_flutter/Notice/1583237505.jpg]
I/flutter ( 3664): ::Mosquitto client connected

════════ Exception caught by image resource service ════════════════════════════════════════════════
The following _Exception was thrown resolving an image codec:
Exception: Could not instantiate image codec.

When the exception was thrown, this was the stack: 
#0      _futurize (dart:ui/painting.dart:4304:5)
#1      instantiateImageCodec (dart:ui/painting.dart:1682:10)
#2      PaintingBinding.instantiateImageCodec (package:flutter/src/painting/binding.dart:88:12)
#3      FileImage._loadAsync (package:flutter/src/painting/image_provider.dart:653:24)
<asynchronous suspension>
...
Path: /data/user/0/com.stellar.dnb/app_flutter/Notice/1583231584.jpg
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ (2) Exception caught by image resource service ════════════════════════════════════════════
Exception: Could not instantiate image codec.
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ (3) Exception caught by image resource service ════════════════════════════════════════════
Exception: Could not instantiate image codec.
════════════════════════════════════════════════════════════════════════════════════════════════════

Мой фрагмент кода:

getAssetList() async {
    response =
        await http.post(_noticeURL, body: parseJson.convertToJson(deviceID));
    if (response.statusCode == 200) {
      parseJson.decodeJson(response.body.toString());
      await downloadAsset(addNoticeToList());
    } else
      print('HTTP Response StatusCode: ${response.statusCode}');
  }

  addNoticeToList() {
    List _assetList = [];
    if (parseJson.responseJsonDecoded.isNotEmpty) {
      for (dynamic value in parseJson.responseJsonDecoded.values) {
        for (dynamic notice in value) {
          _assetList.add(notice);
        }
      }
      return _assetList;
    }
  }

  downloadAsset(List assetList) async {
    //imgList.clear();
    String _dirPath = await dirManager.createFolderInAppDocDir('Notice');
    for (String _asset in assetList) {
      var assetResponse = await http.get(_noticeDownloadURL + _asset);
      var _filePathAndName = (p.join(_dirPath, _asset));
      imgList.add(_filePathAndName);
      File imageFile = File(_filePathAndName);
      print(assetResponse);
      imageFile.writeAsBytesSync(assetResponse.bodyBytes);
    }
    print('$imgList');
  }

1 Ответ

0 голосов
/ 04 марта 2020

Хорошо, проблема решена. URL был неверным, следовательно, ошибка.

...