“对象?”类型的值无法分配给“Map
尝试更改变量的类型,或者将右侧类型转换为“Map
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);
});
}
});
}
您可以通过强制转换为
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);
});
}
}
});
}