read data from firestore flutter
473
The ??
operation is a conditional operation, essentially a shorthand for:
a != null ? a : b
That is not what you want though, you want the field from the document, and only return null
if there is no document. That is done with a single ?
:
print("get score ${document?["score"]}");
I recommend reading the Dart documentation on conditional expressions and the cheat sheet on null-aware operators.
Author by
a.snss
Updated on January 03, 2023Comments
-
a.snss over 1 year
I have a collection of users in firestore. I will print the user's score information from this collection to the screen. I'm doing this with StreamBuilder. When I print the incoming value on the screen, this is the value returned to me.
get score Instance of '_JsonDocumentSnapshot'
@override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return SafeArea( child: Scaffold( appBar: buildAppBar(), body: StreamBuilder( stream: FirebaseFirestore.instance .collection('users') .doc(userID) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) { return const CircularProgressIndicator(); } var document = snapshot.data; print("get score ${document??["score"]}"); return Column( children: <Widget>[ SizedBox( height: size.height * 0.2, child: Stack( children: <Widget>[ Container( height: size.height * 0.2 - 27, decoration: BoxDecoration( color: kPrimaryColor, borderRadius: const BorderRadius.only( bottomLeft: Radius.circular(24), bottomRight: Radius.circular(24), )), child: yourBestScore(), ), Positioned( bottom: 0, left: 0, right: 0, child: howToPlay(), ), ], ), ), const SizedBox( height: 20, ), Expanded( child: Container( margin: const EdgeInsets.all(8), padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(4)), child: const UserInformation()), ), const SizedBox(height: 60), ], ); }, ), floatingActionButton: floatingActionButton(context), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, ), ); }