'How to dynamically update list elements for chart data in Flutter

Im trying to create a chart that updates the data by checking every 4 seconds. It checks if the last element of the list is the same as the single element in another list. If not, it will remove the first element and add the newest element in. However this is not updating my graph and it only stays as the initial data. Help please ?

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,
    );
  }
}


Solution 1:[1]

Add SfCartesianChart inSide Future Builder and Update future of FutureBuilder when you want to update like below code.

FutureBuilder( future: futureDailyCount,

                          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()
                            );
                          }
                      ),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fayyaz kharl