如何在Cloud Fire Store中将文档ID设置为用户uid? [英] how can I set my document id as user uid in cloud fire store?
本文介绍了如何在Cloud Fire Store中将文档ID设置为用户uid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
}
class Test extends StatelessWidget {
//final db = FirebaseFirestore.instance;
//Here I have set my own controller name
TextEditingController sampledata1 = new TextEditingController();
TextEditingController sampledata2 = new TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
centerTitle: true,
backgroundColor: Colors.red[600],
),
body: Container(
padding: EdgeInsets.all(40.0),
child: Center(
child: Column(
children: <Widget> [
TextFormField(
controller: sampledata1,
decoration: InputDecoration(
hintText: "Simple data 1"
),
),
SizedBox(height: 10.0,),
TextFormField(
controller: sampledata2,
decoration: InputDecoration(
hintText: "Simple data 2"
),
),
SizedBox(height: 10.0,),
FlatButton(
onPressed: () async {
//Here I am trying to add document on firestore with users uid but could not get any solution
final uid = await Provider.of(context).auth.getCurrentUID();
Map <String, dynamic> data = {"field1": sampledata1.text, "field2": sampledata2.text};
//FirebaseFirestore.instance.collection("UserData").add(data);
},
child: Text('Submit'),
color: Colors.red[600],
)
],
),
),
),
);
}
}
推荐答案
调用 add(...)
时,Firestore会自动为您生成新文档的ID.
When you call add(...)
Firestore auto-generates an ID for the new document for you.
如果要自己控制ID,请使用 doc(uid).set(...)
:
If you want to control the ID yourself, use doc(uid).set(...)
:
FirebaseFirestore.instance.collection("UserData").doc(uid).set(data);
这篇关于如何在Cloud Fire Store中将文档ID设置为用户uid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文