发生异常。 _TypeError(“容器”类型不是“字符串”类型的子类型)

时间:2021-01-21 06:07:52

标签: flutter dart

我正在尝试在 CircleAvatar() 中显示用户图像 URL;即使我提供了它,它也显示空错误。还是我做错了?

首先调用Auth方法并设置图像String img,

  AuthMethods _auth = AuthMethods();
  String img;

然后我在 initstate 中实例化

    _auth.getCurrentUser().then((user) async {
      setState(() {
        user.uid;

        img = user.photoUrl

      });
    });
  }

然后在Drawer()

中调用它
  DrawerHeader(
    child: CircleAvatar(
      backgroundColor: Colors.deepOrange,
      radius: 100,
      child: Image(
        fit: BoxFit.cover,
        image: NetworkImage(
              img != null ? img : Container(),  // <== here
            ) ??
            CircularProgressIndicator(),
      ),
    ),
    decoration: BoxDecoration(
      color: Colors.orange,
    ),
  ),

2 个答案:

答案 0 :(得分:1)

NetworkImage 将字符串作为周长,而不是小部件。 在你的情况下:

NetworkImage(
              img != null ? img : Container(),  // <== here
            )

如果 img 即字符串为空,则返回 Container(),但您应该返回一个字符串(也许您可以给出一个空字符串)

答案 1 :(得分:0)

NetworkImage 在其 String 参数中采用图像 URL,在您的情况下,您将图像 URL 或 Widget 传递到此参数中,显然 Widget 不是 String。你的空检查应该像这样在 NetworkImage 之上:

...

image: 
   img != null ? NetworkImage(img) 
               :
            CircularProgressIndicator(),
 //Or container or different desired widget in case image path is null
...