I want to retrieve color from firestore. But everytime I do I get this below error:
The method '[]' was called on null.
Receiver: null
Tried calling: []("color")
Here is my code:
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()),
);
}
I am using statefull widget for this. The the info under document(_userId) is added last as so this will be initially null and so when its null want to access document(widget.rackBookItems.id) for color info. Let me know if need any more information to get solution for this.
when cardColor = false my database will be like this so it can access color from document(widget.rackBookItems.id)
after doing some task the database changes to this below one so cardColor changed to true and also color can be accessed from document(_userId)