How to get value of data retrieved from Dart Flutter Firebase?

Issue

I have a code like this:

  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseFirestore FS = FirebaseFirestore.instance;

  CollectionReference TC = FirebaseFirestore.instance.collection("oneSignal");
  var docs = TC.doc("xcG9kfCWnUK7QKbK37qd");
  var response = await docs.get();
  
  var veriable = response.data();
  print(veriable);

I’m getting an output like this:

{id: 5138523951385235825832}

I only want the value from this output, namely 5138523951385235825832. How can I do that?

Solution

Your response is a DocumentSnapshot, so response.data() returns a Map with all the fields. To get a specific field from it you can do:

var veriable = response.data() as Map;
print(veriable["id"]);

Alternatively you can get the field directly from the response with:

print(response.get("id"));

For situations like that I recommend keeping the documentation handy, in this case for DocumentSnapshot.

Answered By – Frank van Puffelen

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *