首页 > 解决方案 > 在文件管理器中替换图像不会替换应用程序中的图像

问题描述

我在 Firebase 存储上上传了一张图片。并在我的颤振应用程序上访问所述图像,我首先将其下载到设备上,然后使用 FileImage 来显示图像。但是,如果图像发生变化,它仍然显示前一个......这是我的代码

  var error;
  Future getImage() async {
    try {
      var image = await ImagePicker.pickImage(
        source: ImageSource.gallery,
      );
      await FirebaseStorage.instance
          .ref()
          .child(userMap['uid'])
          .putFile(image)
          .onComplete;

      await FirebaseStorage.instance
          .ref()
          .child(userMap['uid'])
          .writeToFile(File(path))
          .future;
      setState(() {
        profile = FileImage(File(path));
      });
    } catch (e) {
      error = e;
    }
  }

以下代码显示图像...

GestureDetector(
   onTap: () {
     getImage();
   },
   child: CircleAvatar(
     child: Icon(
     Icons.add_a_photo,
     color: color2.withOpacity(0.5),
     ),
     radius: widget.height * 0.05,
     backgroundColor: color3,
     backgroundImage: profile,
  ),
),

请帮忙

标签: imageflutterdartfirebase-storage

解决方案


我可以向您推荐另一种解决问题的方法。

首先,您不需要使用 FileImage,因为使用它来控制缓存非常困难。

试试下面的代码:

Future<String> uploadImage(File image) async {
  var reference = FirebaseStorage.insance.ref().child(userMap['uid']);
  var uploadTask = reference.putFile(image); // you can just put your file like that
  var snapshot = await uploadTask.onComplete;
  var location = await snapshot.ref.getDownloadURL(); // and get url with it with this code
  return location.toString()
}

Future getImage() async {
  try {
    var image = await ImagePicker.pickImage(
      source: ImageSource.gallery,
    );
    profile = await uploadImage(image)
    setState((){});
  }
  catch (e) {
    error = e;
  }
}

使用 uploadImage 获取 url 地址后,请使用库:https ://pub.dev/packages/cached_network_image 。它非常适合处理图像。

GestureDetector(
   onTap: () {
     getImage();
   },
   child: CircleAvatar(
     child: Icon(
     Icons.add_a_photo,
     color: color2.withOpacity(0.5),
     ),
     radius: widget.height * 0.05,
     backgroundColor: color3,
     backgroundImage: CachedNetworkImageProvider(
        imageUrl: profile,
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),
  ),
),

推荐阅读