【发布时间】:2020-12-06 10:25:35
【问题描述】:
我想从 Firestore 中检索颜色。但每次我这样做时都会出现以下错误:
The method '[]' was called on null.
Receiver: null
Tried calling: []("color")
这是我的代码:
bool cardColor = false;
String _userId;
@override
void initState() {
super.initState();
checkIfColorOrNot();
}
checkIfColorOrNot() async {
FirebaseAuth.instance.currentUser().then((user) {
_userId = user.uid;
});
DocumentSnapshot ds = await Firestore.instance
.collection('rackBookItems')
.document(widget.rackBookItems.id)
.collection('user')
.document(_userId)
.get();
this.setState(() {
cardColor = ds.exists; // If the above if exists then cardColor is turned true else it stays flase
});
}
_cardColorApply(child) {
FirebaseAuth.instance.currentUser().then((user) {
_userId = user.uid;
});
return StreamBuilder(
stream: cardColor
? Firestore.instance
.collection('rackBookItems')
.document(widget.rackBookItems.id)
.collection('user')
.document(_userId)
.snapshots() // this should be shows only when cardColor is true
: Firestore.instance
.collection('rackBookItems')
.document(widget.rackBookItems.id)
.snapshots(), // this should be shows only when cardColor is false
builder: (context, snapshot) {
//Check to make sure snapshot.hasData has data or not
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
int colorValue = int.parse(snapshot.data['color']);
return Card(
color: Color(colorValue),
child: child,
);
},
);
}
@override
Widget build(BuildContext context) {
return InkWell(
onTap: widget.onTap,
child: _cardColorApply(_listItems()),
);
}
我为此使用 statefull 小部件。 document(_userId) 下的信息是最后添加的,因此最初为 null,因此当它的 null 想要访问 document(widget.rackBookItems.id) 以获取颜色信息时。 如果需要更多信息来获得解决方案,请告诉我。
当 cardColor = false 我的数据库将是这样的,因此它可以从 文档(widget.rackBookItems.id)
完成一些任务后,数据库更改为下面的一个,因此 cardColor 更改为 true,并且可以从 document(_userId) 访问颜色
【问题讨论】:
-
它说 snapshot.data 为空。你能告诉我们你的数据库是什么样的吗?
-
是的,我已经添加了您要求的数据库截图。
-
我的意思是你的数据库结构。您可以尝试打印出 snapshot.data 以检查其是否为空吗?
-
当我给 print(snapshot.data);它显示了这一点:I/flutter (31146): 'DocumentSnapshot' 的实例
-
试试这个
!snapshot.hasData && snapshot.data.isNotEmpty
标签: firebase flutter dart google-cloud-firestore