Reputation: 1316
I was trying to sync a users coins and I came across this error: The method [] was called on Null. How do I display his coins dynamically using Firestore?
Widget firestoreBuild2(BuildContext context) {
return StreamBuilder(
stream: Firestore.instance.collection('users').document('id').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasError)
return Text('Error: ${snapshot.error}');
switch (snapshot.connectionState) {
case ConnectionState.waiting: return Text('Loading...');
default:
var userDocument = snapshot.data;
return Text(
userDocument["coins"],
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: AppTheme2.fontName,
fontWeight: FontWeight.normal,
fontSize: 24,
letterSpacing: 0.0,
color: AppTheme2.white,
),
);
}
},
);
}
}
Upvotes: 0
Views: 554
Reputation: 1316
Turns out the reason this was happening is because I was fetching a string 'id' rather than my variable id, which is why it was causing a null error.
Upvotes: 1
Reputation: 3371
snapshot.connectionState has four possible values: none, waiting, active, or done. I'm not sure what the relationship is between the connection state and whether the snapshot has data, exactly.
But one thing you can do is check if snapshot.hasData, which will return false if snapshot.data is null.
Widget firestoreBuild2(BuildContext context) {
return StreamBuilder(
stream: Firestore.instance.collection('users').document('id').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Text('Loading ...');
var userDocument = snapshot.data;
return Text(
userDocument["coins"],
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: AppTheme2.fontName,
fontWeight: FontWeight.normal,
fontSize: 24,
letterSpacing: 0.0,
color: AppTheme2.white,
),
);
},
);
}
}
Upvotes: 0