“对象?”类型的值无法分配给“Map<dynamic, dynamic>?”类型的变量

问题描述 投票:0回答:1

“对象?”类型的值无法分配给“Map?”类型的变量。

尝试更改变量的类型,或者将右侧类型转换为“Map?”。我想将firebase数据库中的点转换为x点来制作折线图。

void fetchDataFromFirebase() {
  final databaseReference = FirebaseDatabase.instance
      .ref('1TJ5Srs0JsEvXaiehwPgCkJ8Ywqsoj5ERRCVcCFhGoDA/swh');

  databaseReference.once().then((DatabaseEvent databaseEvent) {
    if (databaseEvent.snapshot.value != null) {
      Map<dynamic, dynamic>? values = databaseEvent.snapshot.value;
      List<DataPoint> newDataPoints = [];

      values.forEach((key, value) {
        if (value['Num'] != null && value['Swh'] != null) {
          int? num = value['Num'] as int?;
          double? swh = value['Swh'] as double?;

          if (num != null && swh != null && num >= 1 && num <= 10) {
            newDataPoints.add(DataPoint(num.toDouble(), swh));
          }
        }
      });

      setState(() {
        dataPoints.clear();
        dataPoints.addAll(newDataPoints);
      });
    }
  });
}

那么如何使其成为可能呢?在此之前我这样做但仍然出现“foreach”错误

void fetchDataFromFirebase() {
  final databaseReference = FirebaseDatabase.instance
      .ref('1TJ5Srs0JsEvXaiehwPgCkJ8Ywqsoj5ERRCVcCFhGoDA/swh');

  databaseReference.once().then((DataSnapshot dataSnapshot) {
    if (dataSnapshot.value != null) {
      List<DataPoint> newDataPoints = [];

      dataSnapshot.value!.forEach((key, value) {
        if (value['Num'] != null && value['Swh'] != null) {
          int? num = value['Num'] as int?;
          double? swh = value['Swh'] as double?;

          if (num != null && swh != null && num >= 1 && num <= 10) {
            newDataPoints.add(DataPoint(num.toDouble(), swh));
          }
        }
      });

      setState(() {
        dataPoints.clear();
        dataPoints.addAll(newDataPoints);
      });
    }
  });
}
flutter firebase dart foreach linegraph
1个回答
0
投票

您可以通过强制转换为

Map<dynamic,dynamic>?

来避免此问题
void fetchDataFromFirebase() {
  final databaseReference = FirebaseDatabase.instance
      .ref('1TJ5Srs0JsEvXaiehwPgCkJ8Ywqsoj5ERRCVcCFhGoDA/swh');

  databaseReference.once().then((DatabaseEvent databaseEvent) {
    if (databaseEvent.snapshot.value != null) {
      Map<dynamic, dynamic>? values =
          databaseEvent.snapshot.value as Map<dynamic, dynamic>?; // Explicit cast

      if (values != null) { // you shpuld check is it null or not null
        List<DataPoint> newDataPoints = [];

        values.forEach((key, value) {
          if (value['Num'] != null && value['Swh'] != null) {
            int? num = value['Num'] as int?;
            double? swh = value['Swh'] as double?;

            if (num != null && swh != null && num >= 1 && num <= 10) {
              newDataPoints.add(DataPoint(num.toDouble(), swh));
            }
          }
        });

        setState(() {
          dataPoints.clear();
          dataPoints.addAll(newDataPoints);
        });
      }
    }
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.