简体   繁体   中英

How to create unique id for each collection in Firebase?

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)));
                  }
                }
            ),
          ),
        ],
      ),
    );
  }
}

Try this uuid dart package, here is the official Documentation

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

The easiest to guarantee that some value is unique in a collection, is to use that value as the key/ID for the documents in that collection. Since keys/IDs are by definition unique in their collection, this implicitly enforces your requirement.

The only built-in way to generate unique IDs is by calling the add() method, which generates a UUID for the new document. If you don't want to use UUIDs to identify your orders, you'll have to roll your own mechanism.

The two most common approaches:

Generate a unique number and check if it's already taken. You'd do this in a transaction of course, to ensure no two instances can claim the same ID. Keep a global counter (typically in a document at a well-known location) of the latest ID you've handed out, and then read-increment-write that in a transaction to get the ID for any new document. This is typically what other databases do for their built-in auto-ID fields.

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