Reputation: 427
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();
return _snapshot.data()!;
}
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
.
UPD
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();
@override
Widget build(BuildContext context) {
var _data = {};
_query.then((value) => value.forEach((key, value) => _data[key] = value));
inspect(_data);
inspect(_data['name']);
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.
Thanks!
Upvotes: 1
Views: 774
Reputation: 598817
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.
Upvotes: 1