I am making an app that returns a listview showing data from firestore data.
Please look at my code , especially the variable att_topic
.
StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
stream: FirebaseFirestore.instance.collection('userinfo').doc(docsdata.id).snapshots(),
builder: (BuildContext context,
AsyncSnapshot<DocumentSnapshot> snapshot) {
if (!snapshot.hasData) {
return Text("Loading");
}
var data_snap = snapshot.data! as DocumentSnapshot<Map<String,dynamic>>;
var att_topic = data_snap['attended_topic'] ;
return
Column(
children: [
Text(data_snap['via']),
Text(data_snap['myposts'].toString()),
Container(
height: MediaQuery.of(context).size.height*0.4,// ListView for attended topics
child:ListView.builder(
padding: const EdgeInsets.symmetric(vertical: 3),
itemCount: att_topic.length,
itemBuilder: (context, index) {
print(att_topic);
print(att_topic.length);
print(att_topic[index]);
print('^^^^^^^^');
return Text(att_topic[index].toString());
}
)
),
In this code, print(att_topic); print(att_topic.length);print(att_topic[index]); print('^^^^^^^^');
gives me :
I/flutter (15223): {topic_id_220914143250_aSjL7LsloHM6ALWRFCEyke6HQje2: {attended: false, read: true, vote_left: false, vote_right: false}, topic_id_220914135806_aSjL7LsloHM6ALWRFCEyke6HQje2: {attended: true, read: true, vote_left: false, vote_right: true}, topic_id_220914141354_aSjL7LsloHM6ALWRFCEyke6HQje2: {attended: true, read: true, vote_left: false, vote_right: true}}
I/flutter (15223): 3
I/flutter (15223): null
I/flutter (15223): ^^^^^^^^
It seems that att_topic
as template of Map<Map<String,dynamic>>> and definetely has length. So I called att_topic[index]
for print test and ListView but it only returns null
.
Can you please why this happens, and how to solve ?
CodePudding user response:
I think att_topic
is not a list. Hence number-based indexing doesn't work on that. It is a Map
of Maps
.
{
topic_id_220914143250_aSjL7LsloHM6ALWRFCEyke6HQje2: {
attended: false,
read: true,
vote_left: false,
vote_right: false
},
topic_id_220914135806_aSjL7LsloHM6ALWRFCEyke6HQje2: {
attended: true,
read: true,
vote_left: false,
vote_right: true
},
topic_id_220914141354_aSjL7LsloHM6ALWRFCEyke6HQje2: {
attended: true,
read: true,
vote_left: false,
vote_right: true
}
}
Map
-of-Maps
can be accessed like this:
void main() {
final data = {
"topic_id_220914143250_aSjL7LsloHM6ALWRFCEyke6HQje2": {
"attended": false,
"read": true,
"vote_left": false,
"vote_right": false
},
};
print(data.length);
print(data.keys.toList()[0]);
}
So you can access individual item by using keys
getter. There are other ways to do this as well like by using values
getter.
Text(att_topic.keys.toList()[index].toString())
Text(att_topic.values.toList()[index].toString())