Map not empty, but returns null value


I am calling data from firestore like this:

getDoctorData() async {

    DocumentSnapshot<Map<String, dynamic>> _snapshot = await FirebaseFirestore.instance.collection('doctors/1/1').doc('1').get();

I call the function as follows:

final _query = getDoctorData();

Since it’s a Future, I decided to convert it to a simple Map:

var _data = {};
_query.then((value) => value.forEach((key, value) => _data[key] = value));

But for some reason, the data is displayed if I inspect the variable, however, if I specify the key, it returns null.

enter image description here


All the code looks like this:

import 'dart:developer';
import 'package:doc_app/api/get_data.dart';
import 'package:flutter/material.dart';

class DocPage extends StatelessWidget {
  DocPage({Key? key}) : super(key: key);

  final _query = getDoctorData();

  Widget build(BuildContext context) {

  var _data = {};
  _query.then((value) => value.forEach((key, value) => _data[key] = value));
    return SafeArea(
      child: Container(
        decoration: const BoxDecoration(
          color: Color.fromARGB(255, 33, 124, 243),
        child: Column(
        ///// lots of code below

I’m new to dart so I googled a lot but didn’t find an answer to this question.



Since you’re adding the values to _data in an asynchronous then callback, your inspect calls run before the _data is actually populated.

On some environments, inspecting an object is tracked by the environment and then updated when the object is changed (this started in Chrome/WebKit, but I see it elsewhere too these days). But when you log a primitive value, that output is only written when the code executes and not updated later.

So my guess is that the output of inspect(_data); gets retroactively updated when it changes after the statement executed, while the inspect(_data['name']); only writes the value when the statement executes.

Answered By – Frank van Puffelen

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

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