Converting int data to string returns null - Flutter Firestore

Viewed 1015

I have a text field in which if one of the users enters a number it saves to the firestore as an integer. When I try returning the data as a string it says null, even when there is int data for that specific user.

Here is the code for saving the data:


onPressed: () async {
                    try {
                      final String uid = auth.currentUser.uid;
                      FirebaseFirestore.instance
                          .collection('UserNames')
                          .doc(uid)
                          .update({
                        "plastics": int.parse(_plasticController.text),
                      });
                      Navigator.of(context).pop();
                    } catch (e) {}
                  },

And here is my failed attempt at converting it to String and attempting to display it:

First I made a future:


final firestore = FirebaseFirestore.instance; //
    FirebaseAuth auth = FirebaseAuth.instance;
    Future<String> getPlasticNum() async {
      final CollectionReference users = firestore.collection('UserNames');

      final String uid = auth.currentUser.uid;

      final result = await users.doc(uid).get();

      return result.data()['plastics'];
    }

Then I tried to display it:


FutureBuilder(
          future: getPlasticNum(),
          builder: (_, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(child: CircularProgressIndicator());
            }
            return Text(snapshot.data.toString(),
                style: TextStyle(color: Palette.lightGreen, fontSize: 20));
          },
        ),
1 Answers
    Future<String> getPlasticNum()

In here, you tried to get a String value. So you need to convert your data to String.

  return result.data()['plastics'].toString();
Related