Home > database >  How to create unique id for each collection in Firebase?
How to create unique id for each collection in Firebase?

Time:05-16

I want to create a unique id for collection call 'Reservation' and I'm not sure how to do it so. It currently has name, plate number, phone number and timestamp and I would like to create a unique id that holds each document. Can anyone help me on how to create a unique id for this collection? Heres the code that when I insert to the firestore database. Its on the submit button

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_icons/flutter_icons.dart';
import '../model/parking.dart';
class Reservation extends StatelessWidget {


  @override
  Widget build(BuildContext context) {
    final appTitle = 'Car Reservation';
    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: MyCustomForm(),
      ),
    );
  }
}
// Create a Form widget.

class MyCustomForm extends StatefulWidget {

  @override

  MyCustomFormState createState() {

    return MyCustomFormState();
  }

}

// Create a corresponding State class. This class holds data related to the form.

class MyCustomFormState extends State<MyCustomForm> {

  final TextEditingController controller= TextEditingController();
  final TextEditingController name = TextEditingController();
  final TextEditingController phone = TextEditingController();
  final TextEditingController carplate=TextEditingController();



  final GlobalKey<FormState> _formKey=GlobalKey ();

  //firebase instance
  User? user = FirebaseAuth.instance.currentUser;
  Parking loginuser = Parking();
  @override
  void initState(){
    super.initState();
    FirebaseFirestore.instance
        .collection('parkingTech')
        .doc(user!.uid)
        .get()
        .then((value){
      this.loginuser = Parking.fromMap(value.data());
      setState(() {});
    });
  }
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  // final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            controller: name,
            decoration: const InputDecoration(
              icon: Icon(Icons.person),
              hintText: 'Enter your name',
              labelText: "Name",
            ),
            validator: (String? text){
              if (text == null || text.isEmpty){
                return 'Please enter a name';
              }
              return null;
            },
          ),
          TextFormField(
            controller: phone,
            decoration: const InputDecoration(
              icon: Icon(Icons.phone),
              hintText: 'Enter a phone number',
              labelText: 'Phone',
            ),
            validator: (String? text){
              if (text == null || text.isEmpty){
                return 'Please enter a description';
              }
              return null;
            },
          ),
          TextFormField(
            controller: carplate,
            decoration: const InputDecoration(
              icon: Icon(Icons.car_repair_outlined),
              hintText: 'Enter your car plate',
              labelText: 'Plate Number',
            ),
            validator: (String? text){
              if (text == null || text.isEmpty){
                return 'Please enter a description';
              }
              return null;
            },
          ),

          Container (
            padding: const EdgeInsets.only(left: 40.0, top: 40.0),
            child:
            RaisedButton(
                child: const Text('Submit'), //inserting to the firestore database
                onPressed: ()
                async {
                  if (_formKey.currentState!.validate()) {
                    String message;
                    try {
                      final collection =
                      FirebaseFirestore.instance.collection('Reservation');
                      await collection.doc().set({
                        'timestamp': FieldValue.serverTimestamp(),
                        'name': name.text,
                        'phone' : phone.text,
                        'Plate' : carplate.text,
                      });
                      message = 'Success';
                    } catch (_) {
                      // final collection =
                      // FirebaseFirestore.instance.collection('Report');
                      // await collection.doc().set({
                      //   'timestamp': FieldValue.serverTimestamp(),
                      //   'name': name.text,
                      //   'phone' : phone.text,
                      //   'Plate' : carplate.text,
                      // });
                      message = 'Error when sending feedback';
                    }
                    ScaffoldMessenger.of(context)
                        .showSnackBar(SnackBar(content: Text(message)));
                  }
                }
            ),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

Try this uuid dart package, here is the official Documentation

CodePudding user response:

You can use firebase's default method add() or you can use a uuid. I recommend the first.

For the add() method:

FirebaseFirestore.instance.collection('parkingTech').add(value);

For the uuid: Add the package uuid

import 'package:uuid/uuid.dart';

....


final myUuid = const Uuid().v4();

await userCollection.doc(myUuid).set(value);
  • Related