Home > Enterprise >  read data from firestore flutter
read data from firestore flutter

Time:01-30

enter image description here 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,
  ),
);
}

enter image description here

CodePudding user response:

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.

  •  Tags:  
  • Related