[英]How do I get data from a specific field of the specified document inside a Firebase Firestore collection and display it to my UI?
I tried the code below but in the String quantity = snapshot.data()['Quantity'];我尝试了下面的代码,但在字符串 quantity = snapshot.data()['Quantity']; 中function, it returns an error that says The method '[]' can't be unconditionally invoked because the receiver can be 'null'. function,它返回一个错误,指出无法无条件调用方法“[]”,因为接收者可以为“null”。 But when I tried to add a null check to it, it returns another error that says The operator '[]' isn't defined for the type 'Object'.但是当我尝试向它添加 null 检查时,它返回另一个错误,指出运算符 '[]' 没有为类型 'Object' 定义。 How do I make this function work?我如何使这个 function 工作? I'm trying to get data from the field 'Quantity' from the document typed in the Textfield
I made and return a BottomSheet
that shows the current quantity in the database.我正在尝试从我创建的BottomSheet
Textfield
Future<void> _fabFunction(String dropdownValue, String quantityController) async{
DocumentReference docRef = FirebaseFirestore.instance.collection('RAWWillyJKT').doc(_textfieldValue.text);
docRef.get().then((DocumentSnapshot snapshot){
if (snapshot.exists){
Object? data = snapshot.data();
String quantity = snapshot.data()['Quantity'];
_scaffoldKey.currentState?.showBottomSheet((context) => Container(
height: 300,
child: Column(
children: [
Text('$quantity'),
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Dismiss'))
],
),
));
return snapshot.data();
} else {
FirebaseFirestore.instance
.collection('RAWWillyJKT')
.doc(_selectedOption)
.set({
'Jenis': _selectedOption,
'Quantity': quantityController,
'Metric': dropdownValue,
});
}
});
}
You declare data
variable as Object?
您将data
变量声明为Object?
and with this type there is no []
operator.对于这种类型,没有[]
运算符。 The result of data()
(if you don't use a converter) is Map<String, dynamic>?
data()
的结果(如果你不使用转换器)是Map<String, dynamic>?
which does have the []
operator.它确实有[]
运算符。
So if you already made sure that the data is not null, you can use:所以如果你已经确定数据不是null,你可以使用:
final data = snapshot.data()!;
After this you can access the fields:在此之后,您可以访问以下字段:
data['Quantity']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.