我有一个同步融合图表。我想从 firebase 获取数据,但数据仅适用于 xAxis 和 yAxis 只是 datetime 类型。我遇到了一个问题,图表无法从 firebase 获取数据。他们只显示没有数据线的图表。这是我的代码:
@override
Widget build(BuildContext context) {
return MaterialApp(debugShowCheckedModeBanner: false, home: LiveChart());
}
}
class LiveChart extends StatefulWidget {
LiveChart({this.app});
final FirebaseApp app;
@override
_LiveChartState createState() => _LiveChartState();
}
class _LiveChartState extends State<LiveChart> {
int value;
Timer timer;
int count = 0;
final dbRef = FirebaseDatabase.instance.reference();
List<_ChartData> chartData = <_ChartData>[];
Map<dynamic, dynamic> data;
onUpdate() {
setState(() {
value = value;
});
}
void _updateDataSource(Timer timer) {
setState(() {
if (count >= 59) {
count = 0;
}
chartData.add(_ChartData(x: DateTime(2021, 1, 1, count), y1: data['y1']));
if (chartData.length == 20) {
chartData.removeAt(0);
}
count = count + 1;
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(body: _showChart());
}
Widget _showChart() {
return StreamBuilder(
stream: dbRef.child("Data").onValue,
builder: (context, snapshot) {
Widget widget;
if (snapshot.hasData &&
!snapshot.hasError &&
snapshot.data.snapshot.value != null) {
List<dynamic> snaps =
new List(snapshot.data.snapshot.value["Moisture"]);
if (snaps != null && count < snaps.length) {
data = snaps[count];
timer = Timer.periodic(
Duration(milliseconds: 4000), _updateDataSource);
}
widget = Container(
child: SfCartesianChart(
tooltipBehavior: TooltipBehavior(enable: true),
primaryXAxis: DateTimeAxis(),
series: <LineSeries<_ChartData, DateTime>>[
LineSeries<_ChartData, DateTime>(
dataSource: chartData,
xValueMapper: (_ChartData data, _) => data.x,
yValueMapper: (_ChartData data, _) => data.y1,
)
],
),
);
} else {
widget = Center(child: CircularProgressIndicator());
}
return widget;
});
}
@override
void dispose() {
super.dispose();
timer?.cancel();
}
}
class _ChartData {
_ChartData({this.x, this.y1});
final DateTime x;
final int y1;
}
即使他们无法从 firebase 获取数据,我在调试代码时也遇到了错误问题。这是错误:
E/flutter (25491): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter (25491): Receiver: null
E/flutter (25491): Tried calling: []("y1")
我希望任何人都可以帮助我的问题。谢谢!