Home > Software design >  How to set a Sub-Collection as DateTime.Now()?
How to set a Sub-Collection as DateTime.Now()?

Time:01-15

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

CodePudding user response:

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?

  • Related