简体   繁体   English

如何为 Firebase 中的每个集合创建唯一 ID?

[英]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.我想为集合调用“Reservation”创建一个唯一的 ID,但我不确定该怎么做。 It currently has name, plate number, phone number and timestamp and I would like to create a unique id that holds each document.它目前有姓名、车牌号、电话号码和时间戳,我想创建一个唯一的 ID 来保存每个文档。 Can anyone help me on how to create a unique id for this collection?任何人都可以帮助我如何为这个集合创建一个唯一的 id 吗? Heres the code that when I insert to the firestore database.这是我插入到 firestore 数据库时的代码。 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试试这个uuid dart package,这里是官方文档

You can use firebase's default method add() or you can use a uuid.您可以使用 firebase 的默认方法add()或者您可以使用 uuid。 I recommend the first.我推荐第一个。

For the add() method:对于 add() 方法:

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

For the uuid: Add the package uuid对于 uuid:添加 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.保证某个值在集合中唯一的最简单方法是使用该值作为该集合中文档的键/ID。 Since keys/IDs are by definition unique in their collection, this implicitly enforces your requirement.由于键/ID 根据定义在其集合中是唯一的,因此这隐含地强制执行了您的要求。

The only built-in way to generate unique IDs is by calling the add() method, which generates a UUID for the new document.生成唯一 ID 的唯一内置方法是调用 add() 方法,该方法会为新文档生成一个 UUID。 If you don't want to use UUIDs to identify your orders, you'll have to roll your own mechanism.如果您不想使用 UUID 来识别您的订单,则必须推出自己的机制。

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.您当然会在事务中执行此操作,以确保没有两个实例可以声明相同的 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.为您分发的最新 ID 保留一个全局计数器(通常在众所周知位置的文档中),然后在事务中读取-递增-写入该计数器以获取任何新文档的 ID。 This is typically what other databases do for their built-in auto-ID fields.这通常是其他数据库为其内置自动 ID 字段所做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM