Updating Live Data in Flutter Charts – A Complete Guide
Tags: flutter, mobile, dart, webdev
Published: 2021-08-31 16:10:34

---
title: Updating Live Data in Flutter Charts – A Complete Guide
published: true
date: 2021-08-31 10:00:43 UTC
tags: flutter, mobile, dart, webdev
canonical_url: https://www.syncfusion.com/blogs/post/updating-live-data-in-flutter-charts.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6pz5oyq17lz1i8nmf5x.png
---

In many applications, we need to showcase the data that changes over time. A real-time chart is handy at displaying dynamically changing data. By using charts, we can easily convey information and understand the current trends in the data.

Syncfusion [Flutter Charts](https://www.syncfusion.com/flutter-widgets/flutter-charts "Link to Flutter Charts") is a well-crafted charting widget for visualizing data. It contains a rich gallery of 30+ charts and graphs, ranging from line to financial charts, that cater to all charting scenarios. The Flutter Charts also allows you to display live data that changes in minutes or even seconds.

This blog is a complete guide to updating and visualizing live data in your applications using Syncfusion Flutter Charts for:

- [Updating data points](#update-the-data-points).
- [Updating series](#updating-series).
- [Updating data on demand](#updating-data-on-demand).

## Methods

In Flutter Charts, we can use either of the following techniques to update the chart data points live:

1. Call the [setState()](https://api.flutter.dev/flutter/widgets/State/setState.html "Link to the setState method of Flutter Charts") method.
2. Use the [updateDataSource()](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeriesController/updateDataSource.html "Link to the updateDataSource method of Flutter Charts") method of the [ChartSeriesController](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeriesController-class.html "Link to the ChartSeriesController class of Flutter Charts") class.

The **setState()** method will completely process the chart again.  The **updateDataSource()** method will process only the modified item in the data source, and based on that, the corresponding series will be redrawn.

Thus, if you have a huge amount of chart data, we suggest using the **updateDataSource()** method instead of calling the **setState()** method for better performance.

## Updating data points

In this section, we will see how to modify, add, and remove data points in the data source of Flutter Charts.

### Update the values of data points

To update the value of data points, re-initialize the [data source](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries/dataSource.html "Link to the dataSource property of Flutter Charts") collection and use the **setState()** method.

In the following example, we have called the **setState()** method in the **onPressed()** event of a button.

```dart
/// Specifies the list of chart sample data.
List<ChartSampleData> chartData = <ChartSampleData>[
  ChartSampleData(x: 1, y: 30),
  ChartSampleData(x: 3, y: 13),
  ChartSampleData(x: 5, y: 80),
  ChartSampleData(x: 7, y: 30),
  ChartSampleData(x: 9, y: 72)
];

/// Creates an instance of random to generate the random number.
final Random random = Random();

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Center(
      child: Container(
        child: SfCartesianChart(
          primaryXAxis: NumericAxis(),
          primaryYAxis: NumericAxis(),
          series: <ColumnSeries<ChartSampleData, num>>[
            ColumnSeries<ChartSampleData, num>(
              dataSource: chartData,
              xValueMapper: (ChartSampleData data, _) => data.x,
              yValueMapper: (ChartSampleData data, _) => data.y,
              dataLabelSettings: DataLabelSettings(isVisible: true)
            ),
          ],
        )
      ),
    ),
    floatingActionButton: FloatingActionButton(
      onPressed: () => setState(() {
        chartData = <ChartSampleData>[];
        chartData = _getChartData();
      }),
      child: const Icon(Icons.refresh, color: Colors.white),
    )
  );
}

/// Get the random value.
num _getRandomInt(int min, int max) {
  return min + random.nextInt(max - min);
}

/// Method to update the chart data.
List<ChartSampleData> _getChartData() {
  chartData.add(ChartSampleData(x: 1, y: _getRandomInt(10, 100)));
  chartData.add(ChartSampleData(x: 3, y: _getRandomInt(10, 100)));
  chartData.add(ChartSampleData(x: 5, y: _getRandomInt(10, 100)));
  chartData.add(ChartSampleData(x: 7, y: _getRandomInt(10, 100)));
  chartData.add(ChartSampleData(x: 9, y: _getRandomInt(10, 100)));
  return chartData;
}
```

![Updating Data Points in Flutter Charts](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Updating-Data-Points-in-Flutter-Charts.gif)<figcaption>Updating Data Points in Flutter Charts</figcaption>

For more information, refer to the [Updating the Existing Flutter Chart Data Point Value](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/real_time_charts/update_data_source.dart "Link to Updating the Existing Flutter Chart Data Point Value demo on GitHub") project demo.

### Add and remove data points

To proceed further, read about how to use the [updateDataSource()](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeriesController/updateDataSource.html "Link to the updateDataSource method") method to [update the data source of the Flutter Charts](https://help.syncfusion.com/flutter/cartesian-charts/methods#updatedatasource "Link to Update Data Source in Flutter DataGrid documentation").

#### Add data point

Now, follow these steps to add a data point to the existing [data source](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/CartesianSeries/dataSource.html "Link to the dataSource property of Flutter Charts") collection and update it live in the Flutter Charts.

**Step 1:** Add a desired data point into the existing chart data.

```dart
List<ChartSampleData> _addDataPoint() {
  final int length = chartData.length;
  chartData.add(ChartSampleData(x: length, y: _getRandomInt(10, 100)));
  return chartData;
}                        

```

**Step 2:** Then, call the updateDataSource() method in the ChartSeriesController class. Assign the newly added index position to **addedDataIndexes**.

Refer to the following code example.

```dart
IconButton(
  onPressed: () {
    chartData = _addDataPoint();
    _chartSeriesController?.updateDataSource(
      addedDataIndexes: <int>[chartData.length - 1],
    );
  },
);
```

#### Remove data points

Let’s follow these steps to remove the Flutter Chart data points from the existing collection by calling the updateDataSource() of the ChartSeriesController class.

**_Step 1:_**  Remove the unwanted data point from the chart’s data source.

```dart
/// Remove the data point from the series.
List<ChartSampleData> _removeDataPoint() {
  if (chartData.isNotEmpty) {
    chartData.removeAt(chartData.length - 1);
  }
  return chartData;
}
```

**Step 2:** Then, call the updateDataSource() method of the ChartSeriesController class by assigning the removed index position to **updatedDataIndexes** and **removedDataIndexes**.

Refer to the following code example.

```dart
IconButton(
  onPressed: () {
    if (chartData.length > 1) {
      chartData = _removeDataPoint();
      _chartSeriesController?.updateDataSource(
        updatedDataIndexes: <int>[chartData.length - 1],
        removedDataIndexes: <int>[chartData.length - 1],
      );
    }
  },
)
```

**Note:** In both the add and remove data points code examples, the **chartData** is the data point collection set to the [data source](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeries/dataSource.html "Link to the dataSource property of Flutter Charts") property of the chart at loading time.

![Adding and Removing Data Points in Flutter Charts](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Adding-and-Removing-Data-Points-in-Flutter-Charts-1.gif)<figcaption>Adding and Removing Data Points in Flutter Charts</figcaption>

For more information, refer to the [Adding/Removing Data Points in the Flutter Charts](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/real_time_charts/add_remove_data/add_remove_points.dart "Link to Adding/Removing Data Points in the Flutter Charts demo on GitHub") project demo.

## Updating series

Let’s see how to add or remove a series from the [series](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/series.html "Link to the series property of Flutter Charts") collection of a chart using the **setState()** method.

### Add series

**Step 1** : Add the series to the existing series collection of Flutter Chart.

```dart
/// Add series into the chart.
void addSeries() {
  final List<ChartSampleData> chartData1 = <ChartSampleData>[];
  for (int i = 0; i <= 6; i++) {
    chartData1.add(ChartSampleData(x: i, y: _getRandomInt(10, 50)));
  }
  series.add(LineSeries<ChartSampleData, int>(
    key: ValueKey<String>('${series.length}'),
    dataSource: chartData1,
    xValueMapper: (ChartSampleData sales, _) => sales.x as int,
    yValueMapper: (ChartSampleData sales, _) => sales.y,
  ));
}                         

```

**Step 2:** Then, call the **addSeries()** method using the **setState()** in the onPressed event of a button to update the chart with the newly added series.

Refer to the following code example.

```dart
IconButton(
  icon: Icon(Icons.add_circle, size: 50),
  onPressed: () {
    setState(() {
      addSeries();
    });
  }
)                          

```

### Remove series

**Step 1:** Remove the unwanted series from the Flutter Charts series collection.

```dart
///Remove the series from chart.
void removeSeries() {
  if (series.isNotEmpty) {
    series.removeLast();
  }
}                          

```

**Step 2:** In the onPressed event of a button, call the **removeSeries()** method using the **setState()** method to update the removed series.

```dart
IconButton(
  icon: Icon(Icons.remove_circle, size: 50),
  onPressed: () => setState(() {
    removeSeries();
  }),
)                          

```

**Note:** In both the add and remove series examples, the series is the collection of series assigned to the series property of the Flutter Charts widget.

![Adding and Removing a Series in Flutter Charts](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Adding-and-Removing-a-Series-in-Flutter-Charts.gif)<figcaption>Adding and Removing a Series in Flutter Charts</figcaption>

For more information, refer to the [Add/Remove Series Dynamically in a Flutter Chart](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/real_time_charts/add_remove_data/add_remove_series.dart "Link to Add/Remove Series Dynamically in a Flutter Chart demo on GiHub") project demo.

## Updating data on demand

In this section, we are going to see how to lively update the Flutter Charts data automatically at certain intervals and on user interaction.

### Updating data at regular intervals

The Syncfusion Flutter Chart widget acts as a real-time chart that can be easily updated at regular intervals. To achieve this, we are going to use the updateDataSource() method of the ChartSeriesController:

**_Step 1:_** Perform the required activities such as adding or removing data points in the Chart data source, as explained in the [previous section](#update-the-data-points). Then, use the updateDataSource() to update the chart based on the new data point.

```dart
/// Continuously updating the data source based on timer.
void _updateDataSource(Timer timer) {
  chartData.add(_ChartData(count, _getRandomInt(10, 100)));
  if (chartData.length == 20) {
    chartData.removeAt(0);
    _chartSeriesController?.updateDataSource(
      addedDataIndexes: <int>[chartData.length - 1],
      removedDataIndexes: <int>[0],
    );
  } else {
    _chartSeriesController?.updateDataSource(
      addedDataIndexes: <int>[chartData.length - 1],
    );
  }
  count = count + 1;
}                         

```

**Step 2:** Then, initialize a periodic timer. Call the **updateDataSource** method in the timer event to update the chart data continuously at a specific time interval.

Refer to the following code example.

```dart
Timer? timer;

@override
void initState() {
  super.initState();
  timer = Timer.periodic(const Duration(milliseconds: 100), _updateDataSource);
}                          

```

![Updating Flutter Chart Data at Regular Intervals](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Updating-Flutter-Chart-Data-at-Regular-Intervals.gif)<figcaption>Updating Flutter Chart Data at Regular Intervals</figcaption>

For more information, refer to the [Updating Live Data On-Time in Flutter Line Charts](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/real_time_charts/live_update/real_time_line_chart.dart "Link to the Updating Data On-Time in Flutter Line Chart demo on GitHub") project demo.

### On interaction

This section explains how to dynamically update the Flutter Charts live data based on user interaction (dragging and tapping).

#### On drag

Before proceeding, refer to the [On-demand loading in Flutter Cartesian Charts documentation](https://help.syncfusion.com/flutter/cartesian-charts/on-demand-loading "Link to On-demand loading in Flutter Cartesian Charts documentation").

Now, let’s see how to update the Flutter chart’s visible data points by dragging in the chart area.

Here, we are going to load data on demand when the visible axis range reaches its end while dragging using the [loadMoreIndicatorBuilder](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/SfCartesianChart/loadMoreIndicatorBuilder.html "Link to the loadMoreIndicatorBuilder property") property of the Flutter Charts widget:

**Step 1:** Enable the [enablePanning](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanBehavior/enablePanning.html "Link to the enablePanning property") property of the [ZoomPanBehavior](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ZoomPanBehavior-class.html "Link to the ZoomPanBehavior class of Flutter Charts") class to perform dragging in the chart area.

**Step 2:**  Next, create a widget to load more data when the [axis visible range](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/NumericAxis/visibleMaximum.html "Link to the visibleMaximum property of Flutter Charts") reaches the end while dragging.

**Step 3:** Then, return a circular progress indicator until the updated data gets displayed in the chart.

Refer to the following code example.

```dart
/// Returns the load more indicator builder.
Widget getloadMoreIndicatorBuilder(
  BuildContext context, ChartSwipeDirection direction) {
    if (direction == ChartSwipeDirection.end) {
      isNeedToUpdateView = true;
      globalKey = GlobalKey<State>();
      return StatefulBuilder(
        key: globalKey,
        builder: (BuildContext context, StateSetter stateSetter) {
          Widget widget;
          if (isNeedToUpdateView) {
            widget = getProgressIndicator();
            _updateView();
            isDataUpdated = true;
          } else {
            widget = Container();
          }
          return widget;
        });
    } else {
      return SizedBox.fromSize(size: Size.zero);
    }
  }
)                          

```

**Step 4:** As discussed earlier, to update and show the newly added data indexes in the chart, use the updateDataSource() method of the ChartSeriesController class.

```dart
/// Update the chart view based on the newly added data points.
  Future<void> _updateView() async {
    await Future<void>.delayed(const Duration(seconds: 1), () {
      isNeedToUpdateView = false;
      if (isDataUpdated) {
        _updateData();
        isDataUpdated = false;
      }
      if (globalKey.currentState != null) {
        (globalKey.currentState as dynamic).setState(() {});
      }
    });
  }

  /// Method to add new data points to the chart source.
  void _updateData() {
    for (int i = 0; i < 4; i++) {
      chartData.add(ChartSampleData(
          xValue: chartData[chartData.length - 1].xValue + 1,
          y: getRandomInt(0, 600)));
    }
    isLoadMoreView = true;
    seriesController?.updateDataSource(addedDataIndexes: getIndexes(4));
  }

  /// Returns the newly added indexes value.
  List<int> getIndexes(int length) {
    final List<int> indexes = <int>[];
    for (int i = length - 1; i >= 0; i--) {
      indexes.add(chartData.length - 1 - i);
    }
    return indexes;
  }                          

```

![Updating Data by Dragging Interaction in Flutter Charts](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Updating-Data-by-Dragging-Interaction-in-Flutter-Charts.gif)<figcaption>Updating Data by Dragging Interaction in Flutter Charts</figcaption>

For more information, refer to the [Infinite Scrolling in Flutter Charts](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/on_demand_loading/infinite_scrolling.dart "Link to Infinite Scrolling in Flutter Charts demo on GitHub") project demo.

#### On tap

In this section, I will show you how to draw a chart series at a tapped point from the last data point of the chart series. To achieve this, we are going to use the [onChartTouchInteractionUp](https://help.syncfusion.com/flutter/cartesian-charts/callbacks#oncharttouchinteractionup "Link to the onChartTouchInteractionUp callback in Flutter Charts") to get the tapped position on the chart area. To convert a logical pixel value to a chart point value, use the [pixelToPoint](https://help.syncfusion.com/flutter/cartesian-charts/methods#pixeltopoint "Link to the PixelToPoint method of Flutter Charts") method of the ChartSeriesController class.

Refer to the following code example.

```dart
onChartTouchInteractionUp: (ChartTouchInteractionArgs args) {
  final Offset value = Offset(args.position.dx, args.position.dy);
  CartesianChartPoint<dynamic> chartpoint;
  chartpoint = seriesController!.pixelToPoint(value);
  chartData.add(ChartSampleData(x: chartpoint.x, y: chartpoint.y));
  setState(() {});
}                         

```

![Adding New Data Points by Tapping on a Flutter Chart](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Adding-New-Data-Points-by-Tapping-on-a-Flutter-Chart.gif)<figcaption>Adding New Data Points by Tapping on a Flutter Chart</figcaption>

For more information, refer to the [Adding Point On-Click in the Flutter Cartesian Charts](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/user_interactions/add_point_on_click.dart "Link to Adding Point On-Click in the Flutter Cartesian Charts demo on GitHub") project demo.

## Pagination

Also, you can achieve pagination in the Flutter Charts with the [onPlotAreaSwipe](https://help.syncfusion.com/flutter/cartesian-charts/callbacks#onplotareaswipe "Link to the onPlotAreaSwipe callback in Flutter Charts") property. This will help you easily navigate to the desired data in a chart.

![Pagination in Flutter Charts](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Pagination-in-Flutter-Charts.gif)<figcaption>Pagination in Flutter Charts</figcaption>

For more information, refer to the [Pagination in the Flutter Charts demo](https://github.com/syncfusion/flutter-examples/blob/master/lib/samples/chart/cartesian_charts/user_interactions/pagination.dart "Link to Pagination in the Flutter Charts demo on GitHub").

## Conclusion

Thanks for reading! In this blog post, we have seen how to update the live data in your real-time application using the Syncfusion [Flutter Charts widget](https://www.syncfusion.com/flutter-widgets/flutter-charts "Link to the Flutter Charts widget"). Try out the steps given in this blog post and enjoy hassle-free live updates in your real-time charts.

Browse our [documentation](https://help.syncfusion.com/flutter/introduction/overview "Link to Introduction to Syncfusion Flutter Widgets Documentation") to learn more about Syncfusion [Flutter widgets](https://www.syncfusion.com/flutter-widgets "Link to the Syncfusion Flutter UI controls"). You can also see our Syncfusion Flutter app with many examples in this [GitHub repository](https://github.com/syncfusion/flutter-examples "Link to the Syncfusion Flutter demos on GitHub"). Don’t miss our demo app in [Google Play](https://play.google.com/store/apps/details?id=com.syncfusion.flutter.examples&hl=en "Link to the Flutter demos on the Google Play Store"), [App Store](https://apps.apple.com/in/app/syncfusion-flutter-ui-widgets/id1475231341 "Link to the Flutter demos on the App Store"), the [web](https://flutter.syncfusion.com/ "Link to the Flutter demos on web"), [Windows Store](https://www.microsoft.com/en-us/p/syncfusion-flutter-gallery/9nhnbwcsf85d?activetab=pivot:overviewtab "Link to the Flutter demos on the Windows Store"), [macOS](https://install.appcenter.ms/orgs/syncfusion-demos/apps/syncfusion-flutter-gallery/distribution_groups/release "Link to the Flutter demos on the App Center"), and [Snapcraft (Linux)](https://snapcraft.io/syncfusion-flutter-gallery "Link to the Flutter demos on the Snapcraft").

If you aren’t a customer yet, you can try our 30-day [free trial](https://www.syncfusion.com/downloads "Link to the free evaluation of the Syncfusion Essential Studio") to check out our Flutter features.

Finally, if you wish to send us feedback or would like to submit any questions, please feel free to post them in the comments section of this blog post. You can also contact us through our [support forums](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [feedback portal](https://www.syncfusion.com/feedback "Link to Syncfusion Feedback Portal"), or [Direct-Trac support system](https://www.syncfusion.com/support/directtrac/incidents "Link to the Syncfusion support system Direct Trac"). We are always happy to assist you!

## **Related blogs**

- [11 Tips to Improve Your Flutter Development Productivity in Android Studio](https://dev.to/syncfusion/11-tips-to-improve-your-flutter-development-productivity-in-android-studio-57g5 "Link to 11 Tips to Improve Your Flutter Development Productivity in Android Studio blog")
- [7 Best Flutter Charts for Visualizing Income and Expenditure](https://dev.to/syncfusion/7-best-flutter-charts-for-visualizing-income-and-expenditure-2ld7 "Link to 7 Best Flutter Charts for Visualizing Income and Expenditure blog")
- [Spice Up Your Flutter App with Interactive Features in Syncfusion Charts](https://dev.to/syncfusion/spice-up-your-flutter-app-with-interactive-features-in-syncfusion-charts-1jh7 "Link to Spice Up Your Flutter App with Interactive Features in Syncfusion Charts blog")
- [What’s New in 2021 Volume 2: Flutter Charts](https://dev.to/sureshmohan/what-s-new-in-2021-volume-2-flutter-charts-5fg2-temp-slug-6177754 "Link to What’s New in 2021 Volume 2: Flutter Charts blog")