我正在尝试从此数据库中构建项目列表:
但我收到此错误:
_TypeError (type 'List<dynamic>' is not a subtype of type 'List<DataSnapshot>')
我可以使用 snap2.value 获取项目值,但我需要获取元素键,因为它是我的项目 ID,以构建我的列表。
import 'package:firebase_database/firebase_database.dart';
final DatabaseReference _refdata =
FirebaseDatabase.instance.reference().child('host');
getItems() async {
String _refOnline;
await _refdata.child("ref").once().then((value) => _refOnline = value.value);
if (dataRef != _refOnline) {
await _refdata.child("values/valores").once().then((DataSnapshot snap2) {
List<DataSnapshot> result = snap2.value;
lista = result
.map((element) => Item(
element.key,
element.value["nome"],
element.value["preco"].toDouble(),
element.value["precoantes"] ?? "",
element.value["tipo"],
element.value["disponivel"],
element.value["descricao"],
element.value["calorias"]))
.toList();
});
edit:
通过此更改,我能够返回值:
List<Map<dynamic, dynamic>> result =
List<Map<dynamic, dynamic>>.from(snap2.value);
result.forEach((element) {
if (element != null) {
print(element);
}
});
但我无法归还钥匙(1,2,3,4,5)
与执行此操作相同(假设按键排序查询):
List<dynamic> result = snap2.value;
int _i = 1;
result.forEach((value) {
if (value != null) {
lista.add(Item(
_i.toString(),
value["nome"],
value["preco"].toDouble(),
value["precoantes"] ?? "",
value["tipo"],
value["disponivel"],
value["descricao"],
value["calorias"]));
_i += 1;
print(value["nome"]);
print(value);
print(lista.length);
}
现在我收到此错误:
NoSuchMethodError (NoSuchMethodError: The method 'add' was called on null.
Receiver: null
Tried calling: add(Instance of 'Item'))