【问题标题】:flutter firebase firestore: How to remove url from images array list and delete it from cloud storage?flutter firebase firestore:如何从图像数组列表中删除url并将其从云存储中删除?
【发布时间】:2026-02-02 21:00:02
【问题描述】:

我正在使用firebase firestore,并且有我通过firestore获取的图像列表,它们以带索引的数组形式存储,它们在容器内显示良好,当我点击该特定图像时,它会提供完整视图然后在那个特定的上面有一个删除图标按钮,然后按下我正在尝试以下不起作用的代码,我按照此链接“https://petercoding.com/firebase/2020/05/06/using-firebase-storage-in-flutter/”中的代码,他们提到了“删除图像”标题。 我正在尝试的删除代码是:PS 我想从 Firestore 数组和云存储中删除图像 url。

   class Deletebtn extends StatelessWidget{
   final auth = FirebaseAuth.instance;
   int _currentIndex;

   @override
    Widget build(BuildContext context ) {
return new Padding(padding: const EdgeInsets.all(10.0),
  child: IconButton(
    icon: Icon(Icons.delete_forever_outlined,
      color: const Color(0xFF227770),
      size: 35,
    ),
    onPressed: () async {


      var val =[];
      FirebaseFirestore.instance.collection("users").
      doc(auth.currentUser.uid).update
        ({ "images" : FieldValue.arrayRemove(val)}).then((_){
        val.forEach((result) {
          FirebaseStorage.instance.refFromURL(result.data()['images'[_currentIndex]])
              .then((val){
            val.delete().then((val){
              print('deleted');

            });
          });
        });


      });
     },
  ),
);
   }

完整代码:

 class PortfolioGalleryDetailPageTWO extends StatefulWidget{
 final List<String> imageList;
  final int currentIndex;

  PortfolioGalleryDetailPageTWO({Key key, @required this.imageList,@required this.currentIndex})
  : super(key: key);

  @override
 _PortfolioGalleryDetailPageTWO createState() => _PortfolioGalleryDetailPageTWO();
 }

  class _PortfolioGalleryDetailPageTWO extends       State<PortfolioGalleryDetailPageTWO>{
  int _currentIndex;
  PageController _pageController;

  @override
 void initState(){
  super.initState();
_currentIndex = widget.currentIndex;
_pageController = PageController(initialPage: _currentIndex);
   }

  final auth = FirebaseAuth.instance;
  final _storage = FirebaseStorage.instance;


  @override
 Widget build (BuildContext context){

  return Scaffold(
  backgroundColor: Colors.black,
  appBar: AppBar(backgroundColor: Colors.black,),
  body: _buildContent(),
);
  }

   Widget _buildContent(){

   return Stack(
     children: [
      _buildPhotoViewGallery(),
      _buildIndicator(),
      _deleteImage(),
    ],
   );
}

  Widget _deleteImage(){
   return Positioned(
  right: -2,
  top: -9,
  child: new Deletebtn(),
);
 }



  Widget _buildIndicator(){
  return Positioned(
  bottom: 2.0,
  left: 2.0,
  right: 2.0,
  // child: _buildDot(),
  child: _buildDottedIndicator(),
  );
}

  Row _buildDottedIndicator(){
   return Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: widget.imageList.map<Widget>((String imageList)
    => _buildDot(imageList)).toList(),
  );
  }

  Container _buildDot(String imageList){
  return Container(

    width: 5,
  height: 5,
  margin: EdgeInsets.symmetric(vertical: 10.0,horizontal: 2.0),
  decoration: new BoxDecoration(
      color: _currentIndex ==    widget.imageList.indexOf(imageList) ? Colors.red : Colors.white,

        borderRadius: new BorderRadius.circular(2.5),
         boxShadow: [
        new BoxShadow(
            color: Colors.red,
            blurRadius: 10.0,
            spreadRadius: 0.0,
            offset: const Offset(0.0, 1.0))
      ]),

);
  }


  PhotoViewGallery _buildPhotoViewGallery(){
  return PhotoViewGallery.builder(
  itemCount: widget.imageList.length,
  builder: (BuildContext context,int index){
    return PhotoViewGalleryPageOptions(
      imageProvider: NetworkImage(widget.imageList[index]),
      minScale: PhotoViewComputedScale.contained * 0.8,
      maxScale: PhotoViewComputedScale.covered * 1.8,
    );
  },
  scrollPhysics: const BouncingScrollPhysics(),
  pageController: _pageController,
  onPageChanged: (int index){
    setState(() {
      _currentIndex = index;
    });
  },
  scrollDirection: Axis.horizontal,
);
  }



 }

  class Deletebtn extends StatelessWidget{
  final auth = FirebaseAuth.instance;
  int _currentIndex;


    @override
   Widget build(BuildContext context ) {
return new Padding(padding: const EdgeInsets.all(10.0),
  child: IconButton(
    icon: Icon(Icons.delete_forever_outlined,
      color: const Color(0xFF227770),
      size: 35,
    ),
    onPressed: () async {


      var val =[];
      FirebaseFirestore.instance.collection("users").
      doc(auth.currentUser.uid).update
        ({ "images" : FieldValue.arrayRemove(val)}).then((_){
        val.forEach((result) {
          FirebaseStorage.instance.refFromURL(result.data()['images'[_currentIndex]])
              .then((val){
            val.delete().then((val){
              print('deleted');
            });
          });
        });


      });

    },
  ),
);
 }



}

【问题讨论】:

  • 你想从 firebase_storage 中删除吗?
  • 是的,并从数组列表中删除 url ("images")

标签: firebase flutter google-cloud-firestore


【解决方案1】:

你需要传递你要删除的url,我是通过下面的方式实现的;

为路径添加依赖项。

添加这一行:import 'package:path/path.dart' as Path; 而这一行:import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

将以下内容添加到_PortfolioGalleryDetailPageTWO 并将Deletebtn 的所有用法替换为deleteBtn

  Widget deleteBtn(BuildContext context) {
    final auth = FirebaseAuth.instance;
    return new Padding(
      padding: const EdgeInsets.all(10.0),
      child: IconButton(
        icon: Icon(
          Icons.delete_forever_outlined,
          color: const Color(0xFF227770),
          size: 35,
        ),
        onPressed: () async {
           firebase_storage.Reference photoRef = await firebase_storage
              .FirebaseStorage.instance
              .ref()
              .storage
              .refFromURL(widget.imageList[_currentIndex]);
          try {
            await photoRef.delete();
          } catch (e) {}
          FirebaseFirestore.instance
              .collection("users")
              .doc(auth.currentUser.uid)
              .update({
            "images": FieldValue.arrayRemove([widget.imageList[_currentIndex]])
          });
        },
      ),
    );
  }

【讨论】:

  • 感谢回复,但现在它在“StorageReference”>未定义类下显示红线错误,尝试更改名称并在“小部件”>未定义名称小部件和_currentIndex相同。
  • 更新了代码,你也是在指定类中添加代码吗?
  • 是的,添加到课堂上,请问我可以和你分享我的任何一张桌子吗?
  • 当然你可以在推特上联系我分享链接