DEV Community

Cover image for Importing and Displaying CSV data in flutter.
Anton Wentzel
Anton Wentzel

Posted on

Importing and Displaying CSV data in flutter.

Flutter offers developers a robust platform for building cross-platform mobile applications effortlessly. One common scenario in many applications is the need to import and display CSV (Comma-Separated Values) data. In this tutorial, we’ll delve into how to achieve this in a Flutter app using the file_picker plugin.

Getting Started

Before diving into the implementation, ensure you have Flutter installed on your system. If not, follow the instructions on the Flutter website to get started.

Once Flutter is set up, create a new Flutter project or use an existing one. Then, add the necessary dependencies to your pubspec.yaml file:

dependencies: 
file_picker: ^5.3.3 
csv: ^5.0.2 
path_provider: ^2.1.0 
open_file: ^3.3.2
Enter fullscreen mode Exit fullscreen mode

Run flutter pub get to install the dependencies.

Implementing File Upload And Display

Let’s start by setting up the main entry point of our Flutter app. Here’s the code for the main.dart file:

import 'package:flutter/material.dart'; 
import 'upload_page.dart'; // Importing the UploadPage widget 

void main() { runApp(const MyApp()); } 

class MyApp extends StatelessWidget { 

const MyApp({Key? key}) : super(key: key); 

@override Widget build(BuildContext context) { 

return MaterialApp( 
  title: 'CSV Data Import', 
  theme: ThemeData( 
  colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.deepPurple), 
  useMaterial3: true, ), 
  home: const UploadPage(),
    ); 
  }
 }
Enter fullscreen mode Exit fullscreen mode

In this code, we’ve set up a basic Flutter app with a MyApp widget as the root widget. It sets the title and theme for the app and sets the UploadPage as the initial route.

Next, let’s look at the implementation of the UploadPage widget, where users can upload a CSV file and display its data:

// upload_page.dart 
import 'dart:convert'; 
import 'dart:io'; 
import 'package:file_picker/file_picker.dart'; 
import 'package:flutter/material.dart'; 
import 'package:csv/csv.dart'; 

class UploadPage extends StatefulWidget { 
const UploadPage({Key? key}) : super(key: key); 

@override State<UploadPage> createState() => _UploadPageState(); } 

class _UploadPageState extends State<UploadPage> { 

List<List<dynamic>> _data = []; 
String? filePath;

 @override Widget build(BuildContext context) { 

return Scaffold(
         appBar: AppBar( 
         title: const Text("CSV Data Import"),
       ),
       body: Column( 
               children: [ 
                 ElevatedButton( 
                   child: const Text("Upload File"), 
                   onPressed: () { _pickFile(); },
           ),
             Expanded( 
               child: ListView.builder( 
                        itemCount: _data.length, 
                        itemBuilder: (_, index) { 
                          return ListTile( 
                                   title: Text(_data[index].join(', ')),
                                 );
                         },
             ),
        ),
      ],
   ),
  );
 } 

void _pickFile() async { 
  final result = await FilePicker.platform.pickFiles(allowMultiple: false); 

  if (result == null) return; 

  filePath = result.files.single.path!; 
  final input = File(filePath!).openRead(); 
  final fields = await input .transform(utf8.decoder) .transform(const CsvToListConverter()) .toList(); 
  setState(() { _data = fields; }); 
  }
}
Enter fullscreen mode Exit fullscreen mode

This code sets up the UploadPage widget, where users can upload a CSV file. Once a file is selected, its data is parsed and displayed in a list view.

Conclusion

In this tutorial, we explored how to import and display CSV data in a Flutter app using the file_picker plugin. This functionality can be invaluable for applications that require importing data from external sources, such as spreadsheets or databases. Feel free to customize the code to fit your specific requirements and enhance the functionality of your Flutter app.

GitHub: https://github.com/iDigiSolWeb/coding_samples/tree/main/csv_upload

TURN YOUR APP IDEAS INTO DIGITAL REALITY WITH IDIGISOLWEB

Image description

Top comments (0)