0

I have a page to select images from the gallery and add those urls in a list that will be passed to another page after popping. Everything works fine the first time the user accesses the page, however, when coming back to the Image View with an already populated list (passed as argument), whenever I try to edit/removing elements from it, the list remains the same. But the images I want to delete get removed correctly from the firebase storage.

I will attach the code I am trying to use. I am new to flutter so I will really appreciate your help. If you have any questions about the code feel free to ask!

import 'dart:convert';
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:moneybo/utilities/dialogs/delete_dialog.dart';
import 'package:moneybo/utilities/dialogs/error_dialog.dart';
import 'package:moneybo/utilities/generics/get_arguments.dart';

class ImageView extends StatefulWidget {
  const ImageView({super.key});

  @override
  State<ImageView> createState() => _ImageViewState();
}

class _ImageViewState extends State<ImageView> {
  late final ImagePicker _picker;
  late final ImageCache _cache;
  List<String> imageUrls = [];
  List<bool> isImageSelected = [];
  List<String> imagesToDelete = [];
  String imgs = "";
  bool _isSelected = false;

  @override
  void initState() {
    _picker = ImagePicker();
    _cache = ImageCache();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    List<String>? newImageList;
    final imageList = context.getArgument<String>();
    if (imageList != null && imageList.isNotEmpty) {
      newImageList = (jsonDecode(imageList) as List<dynamic>).cast<String>();
      for (String url in newImageList) {
        if (!imageUrls.contains(url)) {
          imageUrls.add(url);
        }
      }
      imgs = jsonEncode(imageUrls);
      for (String element in imageUrls) {
        isImageSelected.add(false);
      }
    }
    return GestureDetector(
      onTap: () {
        List<bool> newIsImageSelected = [];
        for (String element in imageUrls) {
          newIsImageSelected.add(false);
        }
        setState(() {
          _isSelected = false;
          isImageSelected = newIsImageSelected;
          imagesToDelete = [];
        });
        print(imageUrls);
        // print(imgs);
      },
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          toolbarHeight: 73,
          leading: Padding(
            padding: const EdgeInsets.only(top: 25, left: 5),
            child: TextButton(
              child: const Text(
                "OK",
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
              onPressed: () => Navigator.pop(context, imgs),
            ),
          ),
          actions: [
            Padding(
              padding: const EdgeInsets.only(right: 20, top: 20),
              child: isImageSelected.contains(true)
                  ? IconButton(
                      onPressed: () async {
                        final shouldDelete = await showDeleteDialog(
                            context, "Delete this image(s)?");
                        if (shouldDelete) {
                          for (String deleteImage in imagesToDelete) {
                            imageUrls.removeWhere((image) =>
                                image.hashCode == deleteImage.hashCode);
                            await FirebaseStorage.instance
                                .refFromURL(deleteImage)
                                .delete();
                          }
                          imgs = jsonEncode(imageUrls);
                          List<bool> newIsImageSelected = [];
                          for (String element in imageUrls) {
                            newIsImageSelected.add(false);
                          }
                          _cache.clear();
                          _cache.clearLiveImages();
                          setState(() {
                            isImageSelected = newIsImageSelected;
                            imagesToDelete = [];
                          });
                        }
                      },
                      icon: SizedBox(
                          height: 25,
                          child: Image.asset(
                            "lib/icons/bin.png",
                            color: Colors.white,
                          )))
                  : IconButton(
                      icon: const Icon(Icons.add_a_photo_rounded),
                      onPressed: () async {
                        List<XFile>? images = await _picker.pickMultiImage();

                        String uniqueFileName =
                            DateTime.now().microsecondsSinceEpoch.toString();
                        Reference referenceRoot =
                            FirebaseStorage.instance.ref();
                        Reference referenceDirImages =
                            referenceRoot.child("images");

                        try {
                          for (XFile image in images) {
                            uniqueFileName =
                                (int.parse(uniqueFileName) + 1).toString();
                            Reference referenceImageToUpload =
                                referenceDirImages.child(uniqueFileName);
                            await referenceImageToUpload
                                .putFile(File(image.path));
                            String imageUrl =
                                await referenceImageToUpload.getDownloadURL();
                            imageUrls.add(imageUrl);
                            isImageSelected.add(false);
                          }
                        } catch (error) {
                          if (mounted) {
                            showErrorDialog(context, "$error");
                          }
                        }
                        imgs = jsonEncode(imageUrls);
                        setState(() {});
                      },
                    ),
            ),
          ],
          title: const Padding(
            padding: EdgeInsets.only(top: 30.0),
            child: Text(
              "Add images",
              style: TextStyle(fontSize: 16),
            ),
          ),
          flexibleSpace: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: <Color>[
                    Color.fromRGBO(24, 92, 92, 1),
                    Color.fromRGBO(33, 108, 108, 1),
                    Color.fromRGBO(40, 121, 121, 1),
                    Color.fromRGBO(48, 136, 136, 1),
                    Color.fromRGBO(50, 139, 139, 1),
                    Color.fromRGBO(54, 143, 143, 1),
                    Color.fromRGBO(57, 145, 145, 1),
                  ]),
            ),
          ),
        ),
        body: imageUrls.isNotEmpty
            ? Padding(
                padding: const EdgeInsets.only(top: 20, left: 8, right: 8),
                child: GridView.builder(
                  itemCount: imageUrls.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: imageUrls.length > 1 ? 2 : 1,
                    mainAxisSpacing: imageUrls.isNotEmpty ? 8 : 0,
                    crossAxisSpacing: imageUrls.isNotEmpty ? 8 : 0,
                  ),
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onLongPress: () {
                        setState(() {
                          _isSelected = true;
                        });
                      },
                      child: Container(
                        decoration: BoxDecoration(
                            border: Border.all(
                                color: _isSelected
                                    ? Colors.green
                                    : const Color.fromRGBO(11, 68, 68, 1),
                                width: _isSelected ? 4 : 2),
                            borderRadius:
                                const BorderRadius.all(Radius.circular(20))),
                        child: Stack(
                          children: [
                            Center(
                              child: Image.network(
                                imageUrls[index],
                                fit: BoxFit.contain,
                              ),
                            ),
                            _isSelected
                                ? Align(
                                    alignment: Alignment.topRight,
                                    child: Transform.scale(
                                      scale: 1.3,
                                      child: Checkbox(
                                          side: const BorderSide(
                                              width: 2,
                                              color: Color.fromRGBO(
                                                  11, 68, 68, 1)),
                                          shape: const CircleBorder(),
                                          value: isImageSelected[index],
                                          onChanged: (bool? value) {
                                            setState(() {
                                              isImageSelected[index] = value!;
                                            });
                                            if (isImageSelected[index]) {
                                              if (imagesToDelete.isNotEmpty) {
                                                imagesToDelete.insert(
                                                    index, imageUrls[index]);
                                              } else {
                                                imagesToDelete
                                                    .add(imageUrls[index]);
                                              }
                                            } else if (!isImageSelected[
                                                    index] &&
                                                imagesToDelete.contains(
                                                    imageUrls[index])) {
                                              imagesToDelete
                                                  .remove(imageUrls[index]);
                                            } else {
                                              return;
                                            }
                                            print(imagesToDelete);
                                          }),
                                    ),
                                  )
                                : const SizedBox(),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              )
            : Padding(
                padding: const EdgeInsets.only(bottom: 150),
                child: Center(
                    child: SizedBox(
                  child: Column(
                      mainAxisSize: MainAxisSize.max,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: const [
                        Icon(
                          Icons.image_not_supported_outlined,
                          size: 150,
                          color: Color.fromRGBO(168, 168, 168, 1),
                        ),
                        SizedBox(height: 25),
                        Text(
                          "No images yet",
                          style: TextStyle(
                            color: Color.fromRGBO(168, 168, 168, 1),
                            fontSize: 25,
                          ),
                        )
                      ]),
                )),
              ),
      ),
    );
  }
}

0 Answers0