DEV Community

Cover image for Implement Chart Export in Different Formats in Flutter
Parth
Parth

Posted on

Implement Chart Export in Different Formats in Flutter

In today’s data-driven applications, displaying information through charts and exporting them in multiple formats is a crucial feature. Charts are not just visually engaging—they also help users analyze and interpret data more effectively. With Flutter, implementing chart export functionality across formats such as PDF, PNG, and CSV has become quite straightforward. For companies that need custom data visualizations and export options, the best approach may be to hire Flutter developers who are experienced in creating these dynamic features. In this article, we’ll cover a step-by-step approach to implement chart export in different formats in Flutter, along with some useful tips for efficient chart export.

Implementation

Step 1: Setting Up Your Project
First, create a new Flutter project and add dependencies for charting and exporting. Some popular charting libraries include fl_chart and syncfusion_flutter_charts. For file generation and export functionality, consider using pdf, screenshot, and csv packages.

Adding Dependencies:

In your pubspec.yaml file, add these dependencies:

dependencies:
  flutter:
    sdk: flutter
  fl_chart: ^0.40.0
  syncfusion_flutter_charts: ^20.0.0
  pdf: ^3.6.0
  screenshot: ^0.3.0
  csv: ^5.0.0
Enter fullscreen mode Exit fullscreen mode

Then, run flutter pub get to install the packages.

Step 2: Creating and Displaying a Chart

To begin, create a basic chart using fl_chart or syncfusion_flutter_charts. For this example, let's use a simple line chart that shows sales data over a period.

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';

class SalesChart extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LineChart(
      LineChartData(
        lineBarsData: [
          LineChartBarData(
            spots: [
              FlSpot(1, 1),
              FlSpot(2, 3),
              FlSpot(3, 5),
              FlSpot(4, 4),
              FlSpot(5, 6),
            ],
            isCurved: true,
            barWidth: 2,
            colors: [Colors.blue],
          ),
        ],
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

With the chart set up, let’s move to exporting it in different formats.

Step 3: Exporting the Chart as an Image (PNG)
For exporting the chart as an image, we can use the screenshotpackage. Wrap your chart widget in a Screenshot widget and capture it as a PNG image.

import 'package:screenshot/screenshot.dart';

class ExportChartAsImage extends StatefulWidget {
  @override
  _ExportChartAsImageState createState() => _ExportChartAsImageState();
}

class _ExportChartAsImageState extends State<ExportChartAsImage> {
  ScreenshotController screenshotController = ScreenshotController();

  @override
  Widget build(BuildContext context) {
    return Screenshot(
      controller: screenshotController,
      child: SalesChart(),
    );
  }

  void exportAsImage() async {
    final imageFile = await screenshotController.capture();
    // Save or share the imageFile here
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Exporting the Chart as a PDF
To export the chart in PDF format, we can leverage the pdf package. Convert the chart to an image first, then embed it in a PDF document.

import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/material.dart';

void exportAsPDF(Uint8List chartImage) async {
  final pdf = pw.Document();

  pdf.addPage(
    pw.Page(
      build: (pw.Context context) {
        return pw.Center(
          child: pw.Image(pw.MemoryImage(chartImage)),
        );
      },
    ),
  );

  // Save or share the PDF document here
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Exporting Chart Data as CSV
Exporting chart data in CSV format is useful when users need raw data. Here’s how you can export chart data to a CSV file using the csv package:

import 'package:csv/csv.dart';
import 'dart:io';

void exportDataAsCSV() {
  List<List<dynamic>> rows = [
    ["Time", "Sales"],
    [1, 1],
    [2, 3],
    [3, 5],
    [4, 4],
    [5, 6],
  ];

  String csvData = const ListToCsvConverter().convert(rows);
  final file = File('chart_data.csv');
  file.writeAsString(csvData);

  // Save or share the CSV file here
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Exporting charts in various formats, such as PNG, PDF, and CSV, greatly enhances the flexibility of a Flutter app. Implementing this functionality allows users to easily access and share data, catering to diverse requirements. If your app's data requirements are extensive, consider hiring a dedicated Flutter developer with a strong grasp of data visualization to help you build and maintain these functionalities.

This tutorial provides a foundation for adding chart export features to your Flutter app, making it more versatile and user-friendly. Flutter’s capabilities in managing and exporting data can significantly enhance the functionality and appeal of your application, and with the right team in place, your app will meet the needs of even the most data-driven users.

Top comments (0)