如何在Flutter中动态更新图表数据的列表元素



我试图创建一个图表,通过每4秒检查一次来更新数据。它检查列表的最后一个元素是否与另一个列表中的单个元素相同。如果没有,它将删除第一个元素,并在中添加最新的元素。但是,这不会更新我的图形,它只是作为初始数据。请帮忙?

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'globalvar.dart';
import 'home_screen.dart';
import 'chartjsonparse.dart';
class RealHumidityChart extends StatefulWidget {
@override
_RealHumidityChartState createState() => _RealHumidityChartState();
}
class _RealHumidityChartState extends State<RealHumidityChart> {
List<SensorData> chartData = []; // list for storing the last parsed Json data
List<SensorData> singleData = [];
Timer _clearTimer;
Future<String> getChartJsonFromDatabase() async {
// Sending get(url) request using the http client to retrieve the response.
var fullResponse = await http.get(fullUrl);
return fullResponse.body;
}
Future loadSensorData() async {
String jsonString = await getChartJsonFromDatabase(); // Deserialization Step #1
final jsonResponse = json.decode(jsonString); // // Deserialization Step #2
setState(() {
// Mapping the retrieved json response string and adding the sensor data to the chart data list.
for (Map i in jsonResponse) {
chartData.add(
SensorData.fromJson(i) // Deserialization step #3
);
}
});
}
Future loadSingleData() async {
var singleResponse = await http.get(singleUrl);
if (singleResponse.statusCode == 200) {
final singleJsonResponse = json.decode(singleResponse.body);
for (Map i in singleJsonResponse) {
singleData.add(
SensorData.fromJson(i)
);
print("Sucessfully connect singlecode");
print(chartData);
}
}
}
@override
void initState() {
loadSensorData();
_clearTimer = Timer.periodic(Duration(seconds: 4), (Timer t) {
singleData.clear();
loadSingleData();
if (chartData.last != singleData.last){
chartData.removeAt(0);
chartData.add(singleData.last);
setState(() {});
}
});
super.initState();
}
@override
void dispose() {
_clearTimer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff264653),
),
body: SfCartesianChart(
margin: EdgeInsets.all(15),
primaryXAxis: CategoryAxis(
title: AxisTitle(
text: "Date",
)
),
primaryYAxis: NumericAxis(
// '%' will be append to all Y-axis labels
labelFormat: '{value} %'
),
//Chart Title
title: (ChartTitle(text: 'Humidity')),
//Enable legend
legend: Legend(isVisible: false),
//Enable tooltip
tooltipBehavior: TooltipBehavior(enable: true),
series: <ChartSeries<SensorData, String>>[
LineSeries<SensorData, String>(
name: 'Humidity Chart',
dataSource: chartData,
xValueMapper: (SensorData data, _) => data.date,
yValueMapper: (SensorData data, _) => data.sen1,
//Enable Label Settings
dataLabelSettings: DataLabelSettings(isVisible: true),
markerSettings: MarkerSettings(isVisible: true),
),
]
),
);
}
}
class SensorData {
SensorData(this.date, this.sen1);
String date;
dynamic sen1;
factory SensorData.fromJson(Map<String, dynamic> parsedJson) {
return SensorData(
parsedJson['Date'].toString(),
parsedJson['Sen1'] as dynamic,
);
}
}

在Side Future Builder中添加SfCartesianChart,并在需要更新时更新FutureBuilder的Future,如下代码所示

FutureBuilder(未来:未来每日计数,

builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: <Widget>[
SfCartesianChart(
plotAreaBorderWidth: 0,
title: ChartTitle(text: 'Daily Progress'),
legend: Legend(
isVisible: isCardView ? false : true,
overflowMode: LegendItemOverflowMode.wrap),
primaryXAxis: CategoryAxis(
// Axis will be rendered based on the index values
interval: 1,
labelRotation: 90,
arrangeByIndex: true
),
primaryYAxis: NumericAxis(
edgeLabelPlacement: EdgeLabelPlacement.shift,
// labelFormat: '{value}k',
axisLine: const AxisLine(width: 0),
majorTickLines: const MajorTickLines(color: Colors.transparent)
),
tooltipBehavior: TooltipBehavior(enable: true),
series: <ChartSeries<DailyCount, String>>[
LineSeries<DailyCount, String>(
animationDuration: 2500,
width: 2,
name: '',
markerSettings: const MarkerSettings(isVisible: true),
dataSource: chartDataDailyCount!,
xValueMapper: (DailyCount sensors, _) => sensors.xaxis,
yValueMapper: (DailyCount sensors, _) => sensors.collectCount,
),
]
),
SizedBox(height:50),



//                             Column(children: [
//                               SfCartesianChart(
//                                   plotAreaBorderWidth: 0,
//                                   title: ChartTitle(text: 'Surveyor Progress'),
//                                   legend: Legend(
//                                       isVisible: isCardView ? false : true,
//                                       overflowMode: LegendItemOverflowMode.wrap),
//                                   primaryXAxis: CategoryAxis(
//                                     // Axis will be rendered based on the index values
//                                       interval: 1,
//                                       labelRotation: 90,
//                                       arrangeByIndex: true
//                                   ),
//                                   primaryYAxis: NumericAxis(
//                                       edgeLabelPlacement: EdgeLabelPlacement.shift,
//                                       // labelFormat: '{value}k',
//                                       // minimum: 0,
//                                       // maximum: 12,
//                                       axisLine: const AxisLine(width: 0),
//                                       majorTickLines: const MajorTickLines(color: Colors.transparent)
//                                   ),
//                                   tooltipBehavior: TooltipBehavior(enable: true),
//                                   series: <ChartSeries<SurveyourCount, String>>[
//                                     LineSeries<SurveyourCount, String>(
//                                       animationDuration: 2500,
//                                       width: 2,
//                                       name: '',
//                                       color: Colors.red,
//                                       markerSettings: const MarkerSettings(isVisible: true),
//                                       dataSource: chartDataSurveyourCount,
//                                       xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime1,
//                                       yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount1,
//                                     ),
//                                     LineSeries<SurveyourCount, String>(
//                                       animationDuration: 2500,
//                                       width: 2,
//                                       name: '',
//                                       color: Colors.red,
//                                       markerSettings: const MarkerSettings(isVisible: true),
//                                       dataSource: chartDataSurveyourCount,
//                                       xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime1,
//                                       yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount1,
//                                     ),
//                                     // LineSeries<SurveyourCount, String>(
//                                     //   animationDuration: 2500,
//                                     //   width: 2,
//                                     //   name: '',
//                                     //   color: Colors.green,
//                                     //   markerSettings: const MarkerSettings(isVisible: true),
//                                     //   dataSource: chartDataSurveyourCount,
//                                     //   xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime2,
//                                     //   yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount2,
//                                     // ),
//                                     // LineSeries<SurveyourCount, String>(
//                                     //   animationDuration: 2500,
//                                     //   width: 2,
//                                     //   name: '',
//                                     //   color: Colors.blue,
//                                     //   markerSettings: const MarkerSettings(isVisible: true),
//                                     //   dataSource: chartDataSurveyourCount,
//                                     //   xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime3,
//                                     //   yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount3,
//                                     // ),
//                                     // LineSeries<SurveyourCount, String>(
//                                     //   animationDuration: 2500,
//                                     //   width: 2,
//                                     //   name: '',
//                                     //   color: Colors.yellow,
//                                     //   markerSettings: const MarkerSettings(isVisible: true),
//                                     //   dataSource: chartDataSurveyourCount,
//                                     //   xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime4,
//                                     //   yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount4,
//                                     // ),
//                                     // LineSeries<SurveyourCount, String>(
//                                     //   animationDuration: 2500,
//                                     //   width: 2,
//                                     //   name: '',
//                                     //   color: Colors.black,
//                                     //   markerSettings: const MarkerSettings(isVisible: true),
//                                     //   dataSource: chartDataSurveyourCount,
//                                     //   xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime5,
//                                     //   yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount5,
//                                     // ),
//                                     // LineSeries<SurveyourCount, String>(
//                                     //   animationDuration: 2500,
//                                     //   width: 2,
//                                     //   name: '',
//                                     //   color: Colors.orange,
//                                     //   markerSettings: const MarkerSettings(isVisible: true),
//                                     //   dataSource: chartDataSurveyourCount,
//                                     //   xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime6,
//                                     //   yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount6,
//                                     // ),
//                                     // LineSeries<SurveyourCount, String>(
//                                     //   animationDuration: 2500,
//                                     //   width: 2,
//                                     //   name: '',
//                                     //   color: Colors.pink,
//                                     //   markerSettings: const MarkerSettings(isVisible: true),
//                                     //   dataSource: chartDataSurveyourCount,
//                                     //   xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime7,
//                                     //   yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount7,
//                                     // ),
//
//
//                                   ]
//
//                               ),
// ]
//                             ),
//--------------------------------------------
//   Container(
//       width: 30,
//       height: 30 ,
//       color: Colors.red,
//      ),
// ],)

// FutureBuilder(
// future: futureMonthlyCount,
// builder: (context, snapshot) {
//   if (snapshot.hasData) {
//     return   SfCartesianChart(
//         plotAreaBorderWidth: 0,
//         title: ChartTitle(text: 'Monthly Progress'),
//         legend: Legend(
//             isVisible: isCardView ? false : true,
//             overflowMode: LegendItemOverflowMode.wrap),
//         primaryXAxis: CategoryAxis(
//           // Axis will be rendered based on the index values
//             interval: 1,
//             labelRotation: 90,
//             arrangeByIndex: true
//         ),
//         primaryYAxis: NumericAxis(
//             edgeLabelPlacement: EdgeLabelPlacement.shift,
//             // labelFormat: '{value}k',
//             // minimum: 0,
//             // maximum: 12,
//             axisLine: const AxisLine(width: 0),
//             majorTickLines: const MajorTickLines(color: Colors.transparent)
//         ),
//         tooltipBehavior: TooltipBehavior(enable: true),
//         series: <ChartSeries<MonthlyCount, String>>[
//           LineSeries<MonthlyCount, String>(
//             animationDuration: 2500,
//             width: 2,
//             name: '',
//             markerSettings: const MarkerSettings(isVisible: true),
//
//
//
//
//             dataSource: chartDataMonthlyCount!,
//             xValueMapper: (MonthlyCount sales, _) => sales.xaxis,
//             yValueMapper: (MonthlyCount sales, _) => sales.collectCount,
//           ),
//
//         ]
//
//     );
//   }
//   else {
//     return CircularProgressIndicator();
//   }
// }
// ),



],
);
}
else if (snapshot.hasError) {
// return Text('${snapshot.error}');
return  Column(children: [
Padding(
padding: EdgeInsets.all(60),
child:Text('Internet Connection Problem',style:TextStyle(fontSize: 18))),
FlatButton(
child: Text('Refreash', style: TextStyle(fontSize: 20.0),),
onPressed: () {
check().then((intenet) async {
if (intenet != null && intenet) {
setState(() {
futureDailyCount = fetchDailyCount('all','all','all');
});
print('internet Conneciton present');
}else{
print('internet Conneciton Not present');
showAlertDialogInternetNotPresent(context);
}
});
},
),
]);
}
// By default, show a loading spinner.
return Container(
alignment: Alignment.topCenter,
margin: EdgeInsets.only(top: 40),
child: CircularProgressIndicator()
);
}
),

最新更新