简体   繁体   中英

flutter firebase firestore: How to remove url from images array list and delete it from cloud storage?

I am using firebase firestore and there are list of images which I am getting through firestore and they were stored in form of array with index and they are displaying fine inside the container and when i tap on that particular image it gives full view and then on that particular there is a delete icon button on it and on pressing that I am trying the following code which is not working, I followed the code from this link " https://petercoding.com/firebase/2020/05/06/using-firebase-storage-in-flutter/ " where they mentioned "Deleting an Image" Heading. The code for deleting which I was trying is: 在此处输入图像描述 PS I want to delete the image url from array which is firestore and also from cloud storage.

   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');

            });
          });
        });


      });
     },
  ),
);
   }

Complete code:

 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');
            });
          });
        });


      });

    },
  ),
);
 }



}

You need to pass the url which you want to delete, I have implemented it in the following manner;

Add a dependency to for path.

Add this line: import 'package:path/path.dart' as Path; and this line: import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

add the following to _PortfolioGalleryDetailPageTWO and replace all the usages of Deletebtn with 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]])
          });
        },
      ),
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM