enter image description here 已经尝试了几天从我的 Flutter 应用程序中获取 Firestore 中文档的文档 ID。 我想要的是更新或删除文档,但必须先通过他的 id 来识别它。 当我打开 Firestore 时,我有该 ID 和其他值,如姓名、地址等。
现在我想了解如何将文档 ID 放入一个变量中,然后在我的函数中使用它来删除或更新文档。
getDocIndex() {
var documentID = Firestore.instance
.collection('Requests')
.document(widget.data['Document ID'].toString())
.get();
print(documentID);
}
我知道函数中的小部件不可用。也许有snapshot.data ....但它也被标记为红色。
这是我的功能,然后应该可以工作:
deleteDocument(){
Firestore.instance.collection('Requests').document(documentID).delete();
}
答案 0 :(得分:0)
getDocIndex() {
var document = Firestore.instance
.collection('Requests')
.document(widget.data['Document ID'].toString())
.get();
print(document.id);
}
答案 1 :(得分:0)
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kuechenrechner/card_widget.dart';
import 'package:kuechenrechner/gmaps.dart';
import 'package:geocoder/geocoder.dart';
import 'adminslogin.dart';
//final documentsRef = Firestore.instance.collection('Requests');
class Admins extends StatefulWidget {
@override
_AdminsState createState() => _AdminsState();
}
class _AdminsState extends State<Admins> {
/*geoConvert() async {
// Geocoding for Address
// final query = "1600 Amphiteatre Parkway, Mountain View";
var addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");
}
*/
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) {
return AdminsLogin();
}));
}),
title: Text(
'Anfragen',
style: GoogleFonts.lexendDeca(),
),
centerTitle: true,
actions: [
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {
setState(() {});
})
],
),
body: AdminsList(),
);
}
}
Future getPosts() async {
var firestore = Firestore.instance;
QuerySnapshot qn = await firestore
.collection("Requests")
.orderBy('Anfrage vom')
.getDocuments();
return qn.documents;
}
//Abfrage DocumentID
getDocIndex() async {
/* var documentID = Firestore.instance
.collection('Requests')
.document(widget.data['Document ID'].toString())
.get();
print(documentID);
*/
var document = await Firestore.instance
.collection('Requests')
.document(widget.data['Document ID'].toString())
.get();
print(document.id);
}
class AdminsList extends StatefulWidget {
@override
_AdminsListState createState() => _AdminsListState();
}
class _AdminsListState extends State<AdminsList> {
navigateToDetail(DocumentSnapshot post) {
Navigator.push(context,
MaterialPageRoute(builder: (context) => AdminsDetails(post: post)));
}
@override
Widget build(BuildContext context) {
return Container(
child: FutureBuilder(
future: getPosts(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text('Loading...'),
);
} else {
return ListView.separated(
reverse: true,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return ListTile(
title: Text(
'${snapshot.data[index].data['Name']}',
style: GoogleFonts.lexendDeca(),
),
subtitle: Text(
'${snapshot.data[index].data['Anfrage vom']}',
style: GoogleFonts.lexendDeca(),
),
onTap: () => navigateToDetail(snapshot.data[index]),
leading: Icon(
Icons.business_center,
color: Colors.blue,
),
trailing: IconButton(
icon: Icon(Icons.sort),
onPressed: () {
getDocIndex();
}),
);
},
separatorBuilder: (BuildContext context, int index) {
return Divider();
},
);
}
}),
);
}
}
class AdminsDetails extends StatefulWidget {
final DocumentSnapshot post;
AdminsDetails({this.post});
@override
_AdminsDetailsState createState() => _AdminsDetailsState();
}
String keyID;
class _AdminsDetailsState extends State<AdminsDetails> {
//Anfragen löschen intern
deleteDocument() async {
/* CollectionReference collectionReference =
Firestore.instance.collection("Requests");
QuerySnapshot querySnapshot = await collectionReference.getDocuments();
querySnapshot.documents[0].reference.delete();
*/
Firestore.instance.collection('Requests').document(keyID).delete();
}
//Anfragen intern ändern, anpassen! Button in der Appbar!
TextEditingController adminComment = TextEditingController();
updateData() async {
CollectionReference collectionReference =
Firestore.instance.collection("Requests");
QuerySnapshot querySnapshot = await collectionReference.getDocuments();
querySnapshot.documents[0].reference
.updateData({'Administrator Anmerkung': adminComment.text});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Anfrage von ${widget.post.data["Name"]}',
style: GoogleFonts.lexendDeca(),
),
centerTitle: true,
actions: [
IconButton(
icon: Icon(Icons.edit),
onPressed: () {
setState(() {
updateData();
});
})
],
),
body: SingleChildScrollView(
child: Container(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Kontaktdaten des Kunden: ',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
),
TextButton(
onPressed: () => customLaunch(
'mailto:${widget.post.data["Email"]}?subject=Feed%20back&body=Write your%20feedback'),
child: Text('Email: ${widget.post.data["Email"]}',
style: TextStyle(fontSize: 18)),
),
SizedBox(
child: Container(color: Colors.amber),
),
TextButton(
onPressed: () =>
customLaunch('tel: ${widget.post.data["Telefon"]}'),
child: Text('Telefon: ${widget.post.data["Telefon"]}',
style: TextStyle(fontSize: 18)),
),
Divider(),
Text(
'Kundenanschrift: ',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
),
SizedBox(
height: 8.0,
),
TextButton(
child: Text('${widget.post.data["Anschrift"]}'),
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (BuildContext context) {
return MapsDemo();
})),
),
SizedBox(
height: 8.0,
),
Divider(),
Text(
'Kommentar:',
style: TextStyle(fontWeight: FontWeight.w200, fontSize: 18.0),
),
SizedBox(
height: 16.0,
),
Text('${widget.post.data["Kommentar"]}',
style: GoogleFonts.lexendDeca()),
Divider(),
Text(
'Details der Anfrage: ',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w200),
),
SizedBox(
height: 16.0,
),
Text('Anfrage vom: ${widget.post.data["Anfrage vom"]}',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text('Küchenlänge: ${widget.post.data["Küchenlaenge"]} Meter',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text('Hängeschränke: ${widget.post.data["Hängeschränke"]}',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text(
'Gebrauchte Küche: ${widget.post.data["Gebrauchte Küche"]}',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text(
'Arbeitsplatte schneiden: ${widget.post.data["Arbeitsplatte bearbeiten"]}',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text(
'Anschluss Waschmaschine: ${widget.post.data["Anschluss WaMa"]}',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text(
'Anschluss Spülmaschine: ${widget.post.data["Anschluss Spuel"]}',
style: GoogleFonts.lexendDeca()),
SizedBox(
height: 16.0,
),
Text(
'Anschluss Herd: ${widget.post.data["Anschluss Herd"]}',
style: GoogleFonts.lexendDeca(),
),
SizedBox(
height: 16.0,
),
Text(
'Wunschdatum Montage: ${widget.post.data["Wunschdatum"]}',
style: GoogleFonts.lexendDeca(),
),
SizedBox(
height: 16.0,
),
Text(
'Gesamt geschätzt: ${widget.post.data["Gesamt geschätzt"]} Euro',
style: GoogleFonts.lexendDeca(
fontSize: 18,
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline),
),
TextField(
controller: adminComment,
decoration: InputDecoration(
hintText: 'Anmerkung Administrator:',
)),
//Kommentare von Administratoren:
Container(
child: Text(
'${widget.post.data['Administrator Anmerkung']}',
style: GoogleFonts.lexendDeca(),
)),
Column(
children: [
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (BuildContext context) {
return AlertDialog(
title: Text('Diese Anfrage wirklich löschen?',
style: GoogleFonts.lexendDeca()),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Abbrechen')),
TextButton(
onPressed: () async {
setState(() {
deleteDocument();
Navigator.push(context,
MaterialPageRoute(builder:
(BuildContext context) {
return Admins();
}));
});
},
child: Text('Löschen')),
],
);
}));
},
child: Text('Anfrage löschen')),
),
],
),
],
),
),
),
),
);
}
}
答案 2 :(得分:0)
let data = [{"Products":{"xcs2":{"de_DE":{"cat":"45","title":"deutsch - Umrichter","description":"Die Einzelachs-Umrichter .","link":"example.com"},"en_US":{"cat":"4","title":"1ctrlX ","description":"1The single-axis ","link":"1example.com"}},"XCD1":{"de_DE":{"cat":"435","title":"ctrlX ","description":"Die ","link":"example.com"},"en_US":{"cat":"4","title":"2ctrlX ","description":"2The single-axis ","link":"2example.com"}}}}];
const get_found_object = ({ cat: category_id, title, description, link }, material_id) => ({
material_id, category_id, title, description, link
});
function iterateObject(obj, parent_keys = []) {
let result = null;
for (prop in obj) { // prop is the key here (should have de_DE and object)
if (typeof(obj[prop]) == "object") { // obj[prop] is the value.
result = iterateObject(obj[prop], [prop, ...parent_keys]);
if(result) return result;
} else if (prop == "cat" && obj[prop] == 4) {
return get_found_object(obj, parent_keys[1]);
}
}
return null;
}
const result = data.reduce((acc, item) => acc || iterateObject(item), null);
console.log(result);
答案 3 :(得分:0)
如果您知道文档中的值,则可以使用 where 查询来查找具有这些参数的所有文档。
Firestore.instance.collection('requests').where('Document ID', isEqualTo: "ID")
.snapshots().listen(
(data) => print('grower ${data.documents[0]['name']}')
);
但是,如果您已经可以在本地访问文档数据,则可以从文档快照中提取参考路径(如果您已将其存储在本地)。只是在那时从您的应用中恢复该数据的问题。
答案 4 :(得分:0)
谢谢大家!我知道了!
return ListTile(
title: Text(
'${snapshot.data[index].data['Name']}',
style: GoogleFonts.lexendDeca(),
),
subtitle: Text(
'${snapshot.data[index].data['Anfrage vom']}',
style: GoogleFonts.lexendDeca(),
),
onTap: () {
navigateToDetail(snapshot.data[index]);
keyID = snapshot.data[index].data['Document ID'];
print(keyID.toString());
下面我在 keyID 中获取文档中的文档 ID 字段。之后我就可以使用带有ID引用的删除功能了。
Firestore.instance.collection('Requests').document(keyID).delete();