Flutter CSV File - Import and Convert CSV File to List

Published August 10, 2021

In this flutter example we are going to convert csv file to list and display the data into listview. To convert csv file to list we are using the csv file plugin. In this flutter csv example we are going to cover

  • Import CSV file
  • Read data from CSV file and convert to list
  • Display CSV Data to listview

 

 

Download Source code

 

Let's get started

Step 1: Create flutter application

Step 2: Add required libraries into pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter
  csv: ^5.0.0
  path_provider: ^2.0.2
  permission_handler: ^7.1.0
  file_picker: ^3.0.4

 

Step 3: Import CSV File

To import files we are using the file_picker plugin. This file picker has properties like pick a speccific file type. Here we are importing CSV file, so we need to add extention type as FileType.custom

void _openFileExplorer() async {

  try {

    _paths = (await FilePicker.platform.pickFiles(
      type: _pickingType,
      allowMultiple: false,
      allowedExtensions: (_extension?.isNotEmpty ?? false)
          ? _extension?.replaceAll(' ', '').split(',')
          : null,
    ))
        ?.files;
  } on PlatformException catch (e) {
    print("Unsupported operation" + e.toString());
  } catch (ex) {
    print(ex);
  }
  if (!mounted) return;
  setState(() {
    openFile(_paths![0].path);
    print(_paths);
    print("File path ${_paths![0]}");
    print(_paths!.first.extension);

  });
}

 

The above fuction will give you the File path which we selected

 

Step 4: Read data from CSV file

openFile(filepath) async
{
  File f = new File(filepath);
  print("CSV to List");
  final input = f.openRead();
  final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();
  print(fields);
  setState(() {
    employeeData=fields;
  });
}

 

Step 5: Display CSV data on to Listview

We have ready with data which we are converted CSV file to List. Now we need to display these CSV data on to listview by below code

ListView.builder(
    shrinkWrap: true,
    itemCount: employeeData.length,
    itemBuilder: (context,index){
      return Card(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(employeeData[index][0]),
              Text(employeeData[index][1]),
              Text(employeeData[index][2]),
            ],
          ),
        ),
      );
    }),

 

Step 6: Let's run application

Flutter Import CSV file into listview

 

Complete Example code for Export CSV file data to Listview

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

class CsvToList extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {

    return CsvToListState();
  }

}
class CsvToListState extends State<CsvToList>{
  late List<List<dynamic>> employeeData;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<PlatformFile>? _paths;
  String? _extension="csv";
  FileType _pickingType = FileType.custom;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    employeeData  = List<List<dynamic>>.empty(growable: true);
  }
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(title:Text("CSV To List")),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Container(
                color: Colors.green,
                height: 30,
                child: TextButton(
                  child: Text("CSV To List",style: TextStyle(color: Colors.white),),
                  onPressed: _openFileExplorer,
                ),
              ),
            ),
            ListView.builder(
                shrinkWrap: true,
                itemCount: employeeData.length,
                itemBuilder: (context,index){
                  return Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(employeeData[index][0]),
                          Text(employeeData[index][1]),
                          Text(employeeData[index][2]),
                        ],
                      ),
                    ),
                  );
                }),
          ],
        ),
      ),
    );
  }
  openFile(filepath) async
  {
    File f = new File(filepath);
    print("CSV to List");
    final input = f.openRead();
    final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();
    print(fields);
    setState(() {
      employeeData=fields;
    });
  }

  void _openFileExplorer() async {

    try {

      _paths = (await FilePicker.platform.pickFiles(
        type: _pickingType,
        allowMultiple: false,
        allowedExtensions: (_extension?.isNotEmpty ?? false)
            ? _extension?.replaceAll(' ', '').split(',')
            : null,
      ))
          ?.files;
    } on PlatformException catch (e) {
      print("Unsupported operation" + e.toString());
    } catch (ex) {
      print(ex);
    }
    if (!mounted) return;
    setState(() {
      openFile(_paths![0].path);
      print(_paths);
      print("File path ${_paths![0]}");
      print(_paths!.first.extension);

    });
  }
}

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

11952 Views