首页 > 解决方案 > Flutter Firebase Database, DataSnapshot? how to get values and keys, null safe

问题描述

Using firebase_database: ^7.1.1

Before null safety i used to do like this to get the data from firebase database:

DataSnapshot dataSnapshot = await References.getReferenceYears().once();
Map<dynamic, dynamic> values = dataSnapshot.value;
values.forEach((key, value) {...}

Now when i try do like this, i get the error as bellow:

DataSnapshot? dataSnapshot = await References.getReferenceYears().once();
Map<dynamic, dynamic> values = dataSnapshot.value;

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'List<Object?>' is not a subtype of type 'Map<dynamic, dynamic>'

I think this means that the keys are not being returned in the dataSnapshot.value, how can i use this now to get the (key, value) as before?

If I print the snapshot.value I get like this, so looks like the keys are no longer present in the snapshot.value as before, i don't know where are the keys now:

[{name: 2016-2017}, {name: 2017-2018}, {name: 2018-2019}]

Thanks in advance.

标签: flutterdartfirebase-realtime-databasedart-null-safety

解决方案


Try this

DataSnapshot dataSnapshot = await References.getReferenceYears().once();

(dataSnapshot as Map<dynamic, dynamic>).forEach((key, value) {...}

推荐阅读