如何处理无效的URL异常 | Image.network() flutter

huangapple go评论103阅读模式
英文:

How handle with the invalid url exception | Image.network() flutter

问题

我的应用程序有一个输入,用于接收从互联网检索图像的链接,但如果用户输入无效的链接,应用程序会出现问题。

我目前正在使用 Image.network() 来进行图像请求。

如何处理这个异常?

child: ClipRRect(
  borderRadius: BorderRadius.circular(10),
  child: Image.network(imageController.text, fit: BoxFit.cover,)
),

生成的错误:
生成的错误

解决错误并处理抛出的异常。

英文:

My application has an input that receives a link to retrieve an image from the internet, but if the user enters an invalid link, the app breaks.

I'm currently using Image.network() to make the image request.

How to handle this exception?

child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(imageController.text, fit: BoxFit.cover,)
),

Error generated:
Error generated

Resolve the error and handle the thrown exception.

答案1

得分: 0

你可以查看这个答案并使用错误构建器
在你的情况下,你也可以使用三元运算符来检查一个变量:

child: imageController.text.isNotEmpty ? ClipRRect(
  borderRadius: BorderRadius.circular(10),
  child: Image.network(imageController.text, fit: BoxFit.cover),
) : const SizedBox(),
英文:

You can check this answer and use error builder.
You can also in your case check a variable using terniary operator:

child: imageController.text.isNotEmpty ? ClipRRect( borderRadius: BorderRadius.circular(10),   child: Image.network(imageController.text, fit: BoxFit.cover,), ) : const SizedBox(),

答案2

得分: 0

解决方案

你需要创建一个函数来检查URL。

try {
  Image.network('https://example.com/wrong-url.jpg');
} catch (e) {
  // 错误处理代码
  print('错误:$e');
  // 显示自定义错误消息或回退小部件
  // 例如:
  return Text('无效的URL或无法加载图像');
}

并在FutureBuilder中返回它,你也可以使用onErrorBuilder。

Image.network(
      imageUrl,
      errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
        // 自定义错误小部件,在图像加载失败时显示
        return Text('无法加载图像');
      },
      loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
        if (loadingProgress == null)
          return child; // 图像仍在加载中,返回默认占位符
        return CircularProgressIndicator(); // 显示加载指示器
      },
    );

如果选择使用FutureBuilder,可以在函数中处理所有错误。

FutureBuilder<void>(
      future: yourFunction(),
      builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // 图像加载成功
          return Image.network(imageUrl);
        } else if (snapshot.hasError) {
          // 加载图像时发生错误
          return Text('无法加载图像');
        } else {
          // 图像仍在加载中
          return CircularProgressIndicator();
        }
      },
    );
英文:

Solution

you have to future function that check the url

try {
  Image.network('https://example.com/wrong-url.jpg');
} catch (e) {
  // Error handling code
  print('Error: $e');
  // Display a custom error message or fallback widget
  // For example:
  return Text('Invalid URL or Failed to load image');
}

and return it in FutureBuilder also You can use onErrorBuilder

Image.network(
      imageUrl,
      errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
        // Custom error widget to display when image loading fails
        return Text('Failed to load image');
      },
      loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
        if (loadingProgress == null)
          return child; // Image is still loading, return default placeholder
        return CircularProgressIndicator(); // Show a loading indicator
      },
    );

If you choose to use FutureBuilder you can handle all the error in your function

FutureBuilder<void>(
      future: yourFunction()
      builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // Image loaded successfully
          return Image.network(imageUrl);
        } else if (snapshot.hasError) {
          // Error occurred while loading image
          return Text('Failed to load image');
        } else {
          // Image still loading
          return CircularProgressIndicator();
        }
      },
    );

huangapple
  • 本文由 发表于 2023年6月8日 22:13:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76432771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定