首页 > 解决方案 > 如何在flutter中加载后显示网络图像

问题描述

我有一个底部导航栏

Widget bottomNav(int index, PageController pageController){
return CustomNavigationBar(
  currentIndex: index,
  bubbleCurve: Curves.bounceIn,
  scaleCurve: Curves.decelerate,
  selectedColor: constantColors.blueColor,
  unSelectedColor: constantColors.darkColor,
  strokeColor: constantColors.blueColor,
  scaleFactor: 0.1,
  iconSize: 30,
  onTap: (val){
    index = val;
    pageController.jumpToPage(val);
    notifyListeners();
  },
  backgroundColor: Colors.white,
  items: [
    CustomNavigationBarItem(icon: Icon(EvaIcons.home)),
    CustomNavigationBarItem(icon: Icon(EvaIcons.messageCircle)),
    CustomNavigationBarItem(icon: CircleAvatar(
      radius: 35,
      backgroundColor: Colors.transparent,
      backgroundImage: NetworkImage(userAvatar),
    ),
    ),
  ],
);

}

在 backgroundImage 中:我正在处理 NetworkImage => userAvatar 但是当应用程序加载时 userAvatar 的值为 null 因为它需要一些时间来获取图像。但它立即向我抛出了错误,即 url != null 不正确。加载后如何显示图像而没有任何错误。

标签: flutter

解决方案


您可以为此使用cached_network_image

CachedNetworkImage(
  imageUrl: "http://via.placeholder.com/200x150",
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
       ),
    ),
  ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
),

推荐阅读