google / charts

https://pub.dev/packages/charts_flutter
Apache License 2.0
2.8k stars 1.2k forks source link

Update chart with realtime data #732

Open fre391 opened 2 years ago

fre391 commented 2 years ago

Does anybody know, if it is possible to update the state of the chart widget when new data was added. Do I need to call a method of the chart object or should it be enough to call setstate of the widet where the chart is embedded? Thx for feedback!

nurkinali commented 2 years ago

Hello,

If I correctly understood your question, you would like to display real-time data on your chart. I am basically using: ValueNotifier<List<Data>> dataToDisplay = ValueNotifier<List<Data>>([new Data(0, 0)]); Every time I add new data in dataToDisplay, I am notifying listeners.

Then, on the display page, I implemented display method as following:

late List<charts.Series<Data, double>> dataOnScreen;
  initData() {
    dataOnScreen.add(
      charts.Series(
        id: 'Y',
        data: dataToDisplay.value,
        colorFn: (__, _) => charts.ColorUtil.fromDartColor(Color(0xff109618)),late List<charts.Series<Data, double>> dataOnScreen;
  initData() {
    dataOnScreen.add(
      charts.Series(
        id: 'Y',
        data: dataToDisplay.value,
        colorFn: (__, _) => charts.ColorUtil.fromDartColor(Color(0xff109618)),
        domainFn: (Data data, _) => data.time,
        measureFn: (Data data, _) => data.value,
      ),
    );
};

Most importantly, don't forget to call your variable and initialization method at initState:

  @override
  void initState() {
    super.initState();
    dataOnScreen = <charts.Series<Data, double>>[];
    initData();
  }

Lastly, I am basically displaying the data in build Widget:

charts.LineChart (
    dataOnScreen
    defaultRenderer: charts.LineRendererConfig(includeArea: false, stacked: false),
    animate: false,
    primaryMeasureAxis: const charts.NumericAxisSpec(showAxisLine: true,),
    secondaryMeasureAxis: const charts.NumericAxisSpec(showAxisLine: true),
    behaviors: [
        charts.ChartTitle(
            'Values',
            behaviorPosition: charts.BehaviorPosition.bottom,
            titleOutsideJustification: charts.OutsideJustification.middleDrawArea,
         ),
        charts.ChartTitle(
            'Time',
            behaviorPosition: charts.BehaviorPosition.bottom,
            titleOutsideJustification: charts.OutsideJustification.middleDrawArea,
         ),
    ],
);

I don't know if that is the best method but it works.