首页 > 解决方案 > Flutter - 'package:cached_network_image/src/image_provider/_image_provider_io.dart':断言失败:第 20 行 pos 16:'url != null':不正确

问题描述

CachedNetworkImageProvider 需要传递一个非 Null URL。我想做的是:当 _singleCategoryImage 为空时,只需将框着色为默认值,否则显示图像,但无法真正解决。

我收到这个错误。

'package:cached_network_image/src/image_provider/_image_provider_io.dart': Failed assertion: line 20 pos 16: 'url != null': is not true.

资源:


Widget singleCategoryTemp(_singleCategoryText, _singleCategoryImage) {
  return Card(
      elevation: 0,
      color: Colors.transparent,
      child: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            return Container(
              margin: (EdgeInsets.all(MediaQuery.of(context).size.width / 27)),
              child: Center(
                child: Text(
                  _singleCategoryText,
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: MediaQuery.of(context).size.width / 17),
                  textAlign: TextAlign.center,
                ),
              ),
              decoration:
              new BoxDecoration(
                image: DecorationImage(
                  image: CachedNetworkImageProvider(_singleCategoryImage),
                 /* image: NetworkImage(
                      _singleCategoryImage), */
                  fit: BoxFit.cover,
                ),
                // gradient: LinearGradient(colors: [Colors.red, Colors.purple]),
                borderRadius: new BorderRadius.circular(20.0),
                color: Color(0xFF6d6e70)
              ),
            );
          }));
}

标签: flutterdartflutter-layout

解决方案


您可以添加一个三元运算符来评估是否使用图像

decoration: _singleCategoryImage != null
  ? new BoxDecoration(
      image: DecorationImage(
        image: CachedNetworkImageProvider(_singleCategoryImage),
        /* image: NetworkImage(
        _singleCategoryImage), */
        fit: BoxFit.cover,
      ),
      // gradient: LinearGradient(colors: [Colors.red, Colors.purple]),
      borderRadius: new BorderRadius.circular(20.0),
      color: Color(0xFF6d6e70))
  : new BoxDecoration(....), //<==== Your decoration without image

或者也许这个其他选项只是避免加载图像但使用相同的BoxDecoration

  decoration: new BoxDecoration(
      image: _singleCategoryImage != null
          ? DecorationImage(
              image: CachedNetworkImageProvider(_singleCategoryImage),
              /* image: NetworkImage(
_singleCategoryImage), */
              fit: BoxFit.cover,
            )
          : null,
      // gradient: LinearGradient(colors: [Colors.red, Colors.purple]),
      borderRadius: new BorderRadius.circular(20.0),
      color: Color(0xFF6d6e70)))

推荐阅读