1

I have an app where users, every day can take photos of their day and then display them in a Carsoule for that day. For instance, if he takes 10 photos today, all of them go to one subcollection and then display them on one page of the carousel. I tried this solution but didn't work out, Really appreciate the help

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

  @override
  State<Cam> createState() => _CamState();
}

class _CamState extends State<Cam> {
  File? image;
  final db = FirebaseFirestore.instance;       
  final storageRef = FirebaseStorage.instance;
  final ImagePicker _picker = ImagePicker();

  Future cam() async {
    final image = await _picker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    final temImage = File(image.path);

    final fileName = basename(temImage.path);
    final destination = 'files/$fileName';
    try {
      UploadTask uploadTask = storageRef.ref(destination).putFile(temImage);
      String urlRef = await (await uploadTask).ref.getDownloadURL();
      final photo = PhotoModel(ImgUrl: urlRef, dateCreation: DateTime.now());
      final photoToDb = db
          .collection('photos')
          .doc()
          .collection('${DateTime.now()}')
          .withConverter(
            fromFirestore: PhotoModel.fromFirestore,
            toFirestore: ((PhotoModel photoModel, options) =>
                photoModel.toFirestore()),
          );
      photoToDb.add(photo);
    } catch (e) {
      print('errro');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: IconButton(
        onPressed: () {
          cam();
        },
        icon: Icon(
          Icons.camera,
          size: 40,
          color: Colors.red,
        ),
      ),
    );
  }
}

enter image description here

DAni M
  • 683
  • 1
  • 10
  • 21

1 Answers1

1

Since you're addressing the doc with .collection('${DateTime.now()}'), the collection name is based on the timestamp (including the exact time). So that will always be unique.

If you want a single collection per day, you should generate a string with just the date portion of that timestamp. Something like:

.collection(DateFormat('yyyy-MM-dd').format(DateTime.now()))

Also see: How do I format a date with Dart?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Hi, Frank. Really appreciate for taking the time to reply to my question. Coming from Python, knew there should be a .strip method for it. Btw, had to tweak a bit as still create a collection every time users take photo, so the new code will be: .collection('photos') .doc(DateFormat('yyyy-MM-dd').format(DateTime.now())) .collection(DateFormat('KK:mm:ss a').format(DateTime.now())) – DAni M Jan 15 '23 at 08:20