[英]Flutter: The method [] was called on null
我知道這個問題被多次詢問和回答,但我的問題有點不同。 我正在顫動中使用 firebase 實時數據庫。 我在數據庫中為我擁有的現有數據上傳了一個 JSON 文件。 看起來像這樣
每個孩子有 4 個屬性(名稱、位置、質量、大小)孩子的 ID 為 0、1、2.....
當我從我的應用程序創建一個新條目時,孩子有一個隨機 ID,它看起來像這樣。
之后,當我嘗試檢索值時,這些值會打印在控制台中,但在屏幕上我得到:-
The method [] was called on null error. Receiver: null. Tried Calling: []("Name")
我的檢索代碼(我獲取變量並將其傳遞到另一個屏幕):-
ref.once().then((DataSnapshot data) {
datatosend = data;
print(datatosend.value);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DisplayList(
text: datatosend,
title: CategoryItemsitems[index].name),
));
});
我用於顯示列表視圖的代碼:
itemCount: widget.text.value.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
leading: IconButton(
icon: Icon(Icons.edit),
onPressed: () {
print("Edit Pressed!");
}),
title: Text(widget.text.value[index]["Name"]),
subtitle: Text("Quality: " +
widget.text.value[index]["Quality"] +
"\nSize: " +
widget.text.value[index]["Size"] +
"\nLocation: " +
widget.text.value[index]["Location"]),
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.red,
),
onPressed: () {
print("Delete Pressed!");
}),
),
);
}),
我創建新條目的代碼:
databaseReference.child(_category).push().set({
"Name": _name,
"Quality": _quality,
"Size": _size,
"Location": _location
}).then((_) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Successfully Added')));
});
我哪里錯了?
無法訪問代碼就很難知道,但這通常是我遇到此類問題時的做法:
在調試模式下運行代碼並在此行之后放置一個中斷: itemBuilder: (BuildContext context, int index) {
。 通過這種方式,您可以內省widget.text.value
並查看它是否真的是您期望的對象數組。
否則,使用舊的print
並開始在您的 itemBuilder 中打印widget.text.value[index]
(或者甚至先打印widget.text
,然后是widget.text.value
)。 多年來,您會驚訝地發現人類錯誤是如何通過低技術打印功能解決的;-)
祝你好運
大約10天后,我的問題終於解決了。 我做了一些改變:
將數據添加到 Firestore 的代碼。 所有這些都在按鈕的“onpressed”參數中。 所有的輸入都采用一個簡單的形式。
firestoreInstance.collection("cars").add({
"Name": _name,
"Quality": _quality,
"Size": _size,
"Location": _location,
}).then((value) {
print("Added Successfully")});
為了獲取數據並訪問其不同的字段,我使用了流構建器:
StreamBuilder(
stream: Firestore.instance
.collection("cars")
.orderBy("Name") //To display the list by Name
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
else {
if(snapshot.data.documents.length>0)
{
return ListView.builder(
itemCount: snapshot.data.documents.length, //no. of entries fetched
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(
snapshot.data.documents[index].data()["Name"]), //Accessing the Name property
subtitle: Text("Quality: " +snapshot.data.documents[index].data()["Quality"] + //Accessing the Quality property
"\nSize: " +snapshot.data.documents[index].data()["Size"] + //Accessing the Size property
"\nLocation: " +snapshot.data.documents[index].data()["Location"]) //Accessing the Location property
);
}
)}
}
}
}
)
如果某些右括號不匹配,我深表歉意。 我從我非常凌亂的代碼中提取了這些重要的片段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.