Обработка ошибок при загрузке сетевого образа

#flutter #dart

#флаттер #дротик

Вопрос:

Мое приложение отображает много изображений, и некоторые URL-адреса могут быть недопустимыми.

Это код, который я использую для отображения изображения:

(Я использую cached_network_image плагин)

 CachedNetworkImage(
  imageUrl: images.first,
  fit: BoxFit.cover,
  placeholder: (context, url) => Center(
    child: CircularProgressIndicator(),
  ),
  errorWidget: (context, url, error) => Center(
    child: const Icon(Icons.error)
  )
)
 

В принципе, возникает ошибка, которая выдается:

 E/flutter (28425): [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
I/flutter (28425): ══╡ EXCEPTION CAUGHT BY IMAGE RESOURCE SERVICE ╞════════════════════════════════════════════════════
I/flutter (28425): The following _Exception was thrown resolving an image codec:
I/flutter (28425): Exception: operation failed
I/flutter (28425): 
I/flutter (28425): When the exception was thrown, this was the stack:
I/flutter (28425): #0      FileImage._loadAsync (package:flutter/src/painting/image_provider.dart:564:12)
I/flutter (28425): <asynchronous suspension>
I/flutter (28425): #1      FileImage.load (package:flutter/src/painting/image_provider.dart:549:14)
I/flutter (28425): #2      ImageProvider.resolve.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:285:105)
I/flutter (28425): #3      ImageCache.putIfAbsent (package:flutter/src/painting/image_cache.dart:157:22)
I/flutter (28425): #4      ImageProvider.resolve.<anonymous closure> (package:flutter/src/painting/image_provider.dart:285:82)
I/flutter (28425): #5      SynchronousFuture.then (package:flutter/src/foundation/synchronous_future.dart:38:29)
I/flutter (28425): #6      ImageProvider.resolve (package:flutter/src/painting/image_provider.dart:283:30)
I/flutter (28425): #7      _ImageState._resolveImage (package:flutter/src/widgets/image.dart:631:20)
I/flutter (28425): #8      _ImageState.didChangeDependencies (package:flutter/src/widgets/image.dart:606:5)
I/flutter (28425): #9      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3862:12)
I/flutter (28425): #10     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3711:5)
I/flutter (28425): #11     Element.inflateWidget (package:flutter/src/widgets/framework.dart:2956:14)
I/flutter (28425): #12     Element.updateChild (package:flutter/src/widgets/framework.dart:2759:12)
I/flutter (28425): #13     SingleChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4883:14)
I/flutter (28425): #14     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
I/flutter (28425): #15     RenderObjectElement.updateChildren (package:flutter/src/widgets/framework.dart:4601:32)
I/flutter (28425): #16     MultiChildRenderObjectElement.update (package:flutter/src/widgets/framework.dart:4992:17)
I/flutter (28425): #17     Element.updateChild (package:flutter/src/widgets/framework.dart:2748:15)
I/flutter (28425): #18     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3747:16)
I/flutter (28425): #19     Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
I/flutter (28425): #20     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2273:33)
I/flutter (28425): #21     _WidgetsFlutterBindingamp;BindingBaseamp;GestureBindingamp;ServicesBindingamp;SchedulerBindingamp;PaintingBindingamp;SemanticsBindingamp;RendererBindingamp;WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter (28425): #22     _WidgetsFlutterBindingamp;BindingBaseamp;GestureBindingamp;ServicesBindingamp;SchedulerBindingamp;PaintingBindingamp;SemanticsBindingamp;RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:268:5)
I/flutter (28425): #23     _WidgetsFlutterBindingamp;BindingBaseamp;GestureBindingamp;ServicesBindingamp;SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:988:15)
I/flutter (28425): #24     _WidgetsFlutterBindingamp;BindingBaseamp;GestureBindingamp;ServicesBindingamp;SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:928:9)
I/flutter (28425): #25     _WidgetsFlutterBindingamp;BindingBaseamp;GestureBindingamp;ServicesBindingamp;SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:840:5)
I/flutter (28425): #29     _invoke (dart:ui/hooks.dart:209:10)
I/flutter (28425): #30     _drawFrame (dart:ui/hooks.dart:168:3)
I/flutter (28425): (elided 3 frames from package dart:async)
I/flutter (28425): 
I/flutter (28425): Path:
I/flutter (28425): /data/user/0/xx.xxxx.xxxxxxxxxxx/cache/libCachedImageData/31c76660-5970-11e9-b769-3943ba44d1cb.html;
I/flutter (28425): charset=UTF-8
I/flutter (28425): ════════════════════════════════════════════════════════════════════════════════════════════════════

 

Обратите внимание, что этот URL-адрес содержит некоторый HTML-код… так что это нормально

Поскольку я не нашел никакого способа справиться с этой ошибкой, я попытался использовать NetworkImageWithRetry from flutter_image package, используя:

 FadeInImage(
  placeholder: MemoryImage(kTransparentImage),
  image: NetworkImageWithRetry(
    imageUrl
  ),
  fit: BoxFit.cover,
  fadeInDuration: Duration(milliseconds: 150)
)
 

Есть пример ошибки, которая выдается на этот раз:

 [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
I/flutter (31334): ══╡ EXCEPTION CAUGHT BY PACKAGE:FLUTTER_IMAGE ╞═════════════════════════════════════════════════════
I/flutter (31334): The following FetchFailure was thrown NetworkImageWithRetry failed to load
I/flutter (31334): xxxxxxxxxxxxxxxx :
I/flutter (31334): FetchFailure(
I/flutter (31334):   attemptCount: 1
I/flutter (31334):   httpStatusCode: null
I/flutter (31334):   totalDuration: 0:00:05.969844
I/flutter (31334):   originalException: Exception: operation failed
I/flutter (31334): )
I/flutter (31334): ════════════════════════════════════════════════════════════════════════════════════════════════════
 

Этот URL-адрес отправляет HTML-код…

Проблема в том, что в режиме выпуска я принудительно закрываю приложение в случае какой-либо ошибки, поэтому мне нужно их обработать

как я могу просто справиться с такими ошибками?