从 firebase 数据库 flutter 读取项目列表

2024-04-01

我正在尝试从此数据库中构建项目列表:

但我收到此错误:

_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'))

FlutterFire 中无法获取子节点列表DataSnapshot对象。

我得到的最接近的是:

currentRoundListener = dbRoot.child('rounds/$currentRoundKey').once.then((snapshot) {
  currentRound = List<String>.from(snapshot.value as List<dynamic>);
});

你可以尝试一下:

List<DataSnapshot> result = List<DataSnashot>.from(snap2.value as List<dynamic>);

但更有可能的是,快照下的值只能作为地图使用:

Map<String, dynamic> result = Map<String, dynamic>.from(snap2.value as Map<dynamic, dynamic>);

如果需要维护子节点的顺序,请看这里:Flutter:Firebase实时数据库orderByChild对查询结果没有影响 https://stackoverflow.com/questions/61333194/flutter-firebase-real-time-database-orderbychild-has-no-impact-on-query-result/61333575#61333575和这里:Flutter Firebase 数据库时间戳顺序错误 https://stackoverflow.com/questions/51808719/flutter-firebase-database-wrong-timestamp-order/51811808#51811808

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 firebase 数据库 flutter 读取项目列表 的相关文章

随机推荐