簡體   English   中英

如何從 Firebase Firestore 集合中指定文檔的特定字段獲取數據並將其顯示到我的 UI?

[英]How do I get data from a specific field of the specified document inside a Firebase Firestore collection and display it to my UI?

我嘗試了下面的代碼,但在字符串 quantity = snapshot.data()['Quantity']; 中 function,它返回一個錯誤,指出無法無條件調用方法“[]”,因為接收者可以為“null”。 但是當我嘗試向它添加 null 檢查時,它返回另一個錯誤,指出運算符 '[]' 沒有為類型 'Object' 定義。 我如何使這個 function 工作? 我正在嘗試從我創建的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,
        });
      }
    });
  }

您將data變量聲明為Object? 對於這種類型,沒有[]運算符。 data()的結果(如果你不使用轉換器)是Map<String, dynamic>? 它確實有[]運算符。

所以如果你已經確定數據不是null,你可以使用:

final data = snapshot.data()!;

在此之后,您可以訪問以下字段:

data['Quantity']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM