Firestore-Flutter-GetX:如何获取文档 ID 以更新 Firestore 中的记录
Firestore-Flutter-GetX: How to get document id to update a record in Firestore
我对 Dart 很陌生,而且一般来说是编码。我在观看 YouTube 上的教程后制作了这段代码。大多数情况下,我已经能够自己解决大部分问题,但我无法找出最近的错误。我在 firestorm 中成功创建了记录,但我无法更新它,因为我无法获取文档 ID。
这是我的代码:-
import 'package:flutter/material.dart';
import 'package:lms_definer/controllers/profileController.dart';
import 'package:lms_definer/controllers/textController.dart';
import 'package:get/get.dart';
import 'package:lms_definer/model/profileModel.dart';
import 'package:lms_definer/constants/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../helper/firestore_db.dart';
class EditProfile extends StatelessWidget {
const EditProfile({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var _textController = ProfileEdit();
return Scaffold(
body: GetX<ProfileController>(
init: Get.put<ProfileController>(ProfileController()),
builder: (ProfileController profileController) {
return Container(
child: ListView.builder(
itemCount: profileController.profiles.length,
itemBuilder: (BuildContext context, int i) {
final _profileModel = profileController.profiles[i];
setTextEditControllerValue(_textController, _profileModel);
return SafeArea(
child: Container(
padding: EdgeInsets.all(20),
child: Form(
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.fNameController
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.lNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Address',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.adressController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Phone Numbaer',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.phoneController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'School Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.sclNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Student Class',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.stdClassController,
),
SizedBox(
height: 10,
),
ElevatedButton(onPressed: () async {
ProfileModel profileModel = profileModelVal(_textController);
//await FirestoreDb.updateProfile(profileModel, documentId);
}, child: Text('Update'))
],
),
),
),
);
}),
);
},
));
}
ProfileModel profileModelVal(ProfileEdit _textController) {
final profileModel = ProfileModel(
firstName:
_textController.fNameController.text.trim(),
lastName:
_textController.lNameController.text.trim(),
parentName: _textController
.fatherNameController.text
.trim(),
phoneNumber:
_textController.phoneController.text.trim(),
address:
_textController.adressController.text.trim(),
schoolName:
_textController.sclNameController.text.trim(),
stdClass: _textController.stdClassController.text
.trim());
return profileModel;
}
void setTextEditControllerValue(ProfileEdit _textController,
ProfileModel _profileModel) {
_textController.fNameController.value =
TextEditingValue(text: _profileModel.firstName);
_textController.lNameController.value =
TextEditingValue(text: _profileModel.lastName);
_textController.fatherNameController.value =
TextEditingValue(text: _profileModel.parentName);
_textController.adressController.value =
TextEditingValue(text: _profileModel.address);
_textController.phoneController.value =
TextEditingValue(text: _profileModel.phoneNumber);
_textController.sclNameController.value =
TextEditingValue(text: _profileModel.schoolName);
_textController.stdClassController.value =
TextEditingValue(text: _profileModel.stdClass);
}
void clearTextController(ProfileEdit _textController) {
_textController.fNameController.clear();
_textController.lNameController.clear();
_textController.fatherNameController.clear();
_textController.adressController.clear();
_textController.phoneController.clear();
_textController.sclNameController.clear();
_textController.stdClassController.clear();
}
}
我的数据库文件:-
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:lms_definer/constants/constants.dart';
import 'package:lms_definer/model/profileModel.dart';
class FirestoreDb {
static createProfile(ProfileModel profilemodel) async {
await firebaseFirestore.collection('users').doc(auth.currentUser!.uid)
.collection('profile')
.add({
'firstName': profilemodel.firstName,
'lastName': profilemodel.lastName,
'parentName': profilemodel.parentName,
'phoneNumber': profilemodel.phoneNumber,
'address': profilemodel.address,
'schoolName': profilemodel.schoolName,
'stdClass': profilemodel.stdClass,
'createdOn': Timestamp.now(),
'isDone': true
});
}
static Stream<List<ProfileModel>> profileStream() {
return firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.snapshots()
.map((QuerySnapshot query) {
List<ProfileModel> profiles = [];
for (var profile in query.docs) {
final profileModel =
ProfileModel.fromDocmentSnapshot(documentSnapshot: profile);
profiles.add(profileModel);
}
return profiles;
});
}
static updateProfile(ProfileModel profilemodel, documentId ) {
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.doc(documentId)
.update(
{
'firstName': profilemodel.firstName,
'lastName': profilemodel.lastName,
'parentName': profilemodel.parentName,
'phoneNumber': profilemodel.phoneNumber,
'address': profilemodel.address,
'schoolName': profilemodel.schoolName,
'stdClass': profilemodel.stdClass,
'createdOn': Timestamp.now(),
}
);
}
static deleteProfile(String documentID) {
firebaseFirestore.collection('users').doc(auth.currentUser!.uid).collection(
'profile').doc(documentID).delete();
}}
我需要文档 ID 来更新文件。请帮忙。谢谢
一旦用户登录(我假设 EditProfile 页面仅对登录用户可见),您应该将 userId 存储在某处。这可以使用 flutter_secure_storage or using an auth library like FirebaseAuth.
来完成
然后当你想更新用户的文档时,你可以获取之前存储的userId来更新文档。
static updateProfile(ProfileModel profilemodel, documentId ) {
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.get()
.then((QuerySnapshot querySnapshot) {
final docId = queryShapchot.docs.first.id;
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.doc(docId)
.update({
// Add data here
})
});
}
这应该可以解决您的问题。
我对 Dart 很陌生,而且一般来说是编码。我在观看 YouTube 上的教程后制作了这段代码。大多数情况下,我已经能够自己解决大部分问题,但我无法找出最近的错误。我在 firestorm 中成功创建了记录,但我无法更新它,因为我无法获取文档 ID。
这是我的代码:-
import 'package:flutter/material.dart';
import 'package:lms_definer/controllers/profileController.dart';
import 'package:lms_definer/controllers/textController.dart';
import 'package:get/get.dart';
import 'package:lms_definer/model/profileModel.dart';
import 'package:lms_definer/constants/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../helper/firestore_db.dart';
class EditProfile extends StatelessWidget {
const EditProfile({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var _textController = ProfileEdit();
return Scaffold(
body: GetX<ProfileController>(
init: Get.put<ProfileController>(ProfileController()),
builder: (ProfileController profileController) {
return Container(
child: ListView.builder(
itemCount: profileController.profiles.length,
itemBuilder: (BuildContext context, int i) {
final _profileModel = profileController.profiles[i];
setTextEditControllerValue(_textController, _profileModel);
return SafeArea(
child: Container(
padding: EdgeInsets.all(20),
child: Form(
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.fNameController
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'First Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.lNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Address',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.adressController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Phone Numbaer',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.phoneController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'School Name',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.sclNameController,
),
SizedBox(
height: 10,
),
TextFormField(
decoration: const InputDecoration(
labelText: 'Student Class',
border: OutlineInputBorder(
borderSide: BorderSide()),
),
controller: _textController.stdClassController,
),
SizedBox(
height: 10,
),
ElevatedButton(onPressed: () async {
ProfileModel profileModel = profileModelVal(_textController);
//await FirestoreDb.updateProfile(profileModel, documentId);
}, child: Text('Update'))
],
),
),
),
);
}),
);
},
));
}
ProfileModel profileModelVal(ProfileEdit _textController) {
final profileModel = ProfileModel(
firstName:
_textController.fNameController.text.trim(),
lastName:
_textController.lNameController.text.trim(),
parentName: _textController
.fatherNameController.text
.trim(),
phoneNumber:
_textController.phoneController.text.trim(),
address:
_textController.adressController.text.trim(),
schoolName:
_textController.sclNameController.text.trim(),
stdClass: _textController.stdClassController.text
.trim());
return profileModel;
}
void setTextEditControllerValue(ProfileEdit _textController,
ProfileModel _profileModel) {
_textController.fNameController.value =
TextEditingValue(text: _profileModel.firstName);
_textController.lNameController.value =
TextEditingValue(text: _profileModel.lastName);
_textController.fatherNameController.value =
TextEditingValue(text: _profileModel.parentName);
_textController.adressController.value =
TextEditingValue(text: _profileModel.address);
_textController.phoneController.value =
TextEditingValue(text: _profileModel.phoneNumber);
_textController.sclNameController.value =
TextEditingValue(text: _profileModel.schoolName);
_textController.stdClassController.value =
TextEditingValue(text: _profileModel.stdClass);
}
void clearTextController(ProfileEdit _textController) {
_textController.fNameController.clear();
_textController.lNameController.clear();
_textController.fatherNameController.clear();
_textController.adressController.clear();
_textController.phoneController.clear();
_textController.sclNameController.clear();
_textController.stdClassController.clear();
}
}
我的数据库文件:-
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:lms_definer/constants/constants.dart';
import 'package:lms_definer/model/profileModel.dart';
class FirestoreDb {
static createProfile(ProfileModel profilemodel) async {
await firebaseFirestore.collection('users').doc(auth.currentUser!.uid)
.collection('profile')
.add({
'firstName': profilemodel.firstName,
'lastName': profilemodel.lastName,
'parentName': profilemodel.parentName,
'phoneNumber': profilemodel.phoneNumber,
'address': profilemodel.address,
'schoolName': profilemodel.schoolName,
'stdClass': profilemodel.stdClass,
'createdOn': Timestamp.now(),
'isDone': true
});
}
static Stream<List<ProfileModel>> profileStream() {
return firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.snapshots()
.map((QuerySnapshot query) {
List<ProfileModel> profiles = [];
for (var profile in query.docs) {
final profileModel =
ProfileModel.fromDocmentSnapshot(documentSnapshot: profile);
profiles.add(profileModel);
}
return profiles;
});
}
static updateProfile(ProfileModel profilemodel, documentId ) {
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.doc(documentId)
.update(
{
'firstName': profilemodel.firstName,
'lastName': profilemodel.lastName,
'parentName': profilemodel.parentName,
'phoneNumber': profilemodel.phoneNumber,
'address': profilemodel.address,
'schoolName': profilemodel.schoolName,
'stdClass': profilemodel.stdClass,
'createdOn': Timestamp.now(),
}
);
}
static deleteProfile(String documentID) {
firebaseFirestore.collection('users').doc(auth.currentUser!.uid).collection(
'profile').doc(documentID).delete();
}}
我需要文档 ID 来更新文件。请帮忙。谢谢
一旦用户登录(我假设 EditProfile 页面仅对登录用户可见),您应该将 userId 存储在某处。这可以使用 flutter_secure_storage or using an auth library like FirebaseAuth.
来完成然后当你想更新用户的文档时,你可以获取之前存储的userId来更新文档。
static updateProfile(ProfileModel profilemodel, documentId ) {
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.get()
.then((QuerySnapshot querySnapshot) {
final docId = queryShapchot.docs.first.id;
firebaseFirestore
.collection('users')
.doc(auth.currentUser!.uid)
.collection('profile')
.doc(docId)
.update({
// Add data here
})
});
}
这应该可以解决您的问题。