DEV Community

Cover image for Flutter Import CSV file and convert to List
rrtutors
rrtutors

Posted on • Updated on • Originally published at rrtutors.com

Flutter Import CSV file and convert to List

Flutter CSV File Import and display data inside Listview.

This post we are going to cover

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

Alt Text

dependencies:
  flutter:
    sdk: flutter
  csv: ^5.0.0
  path_provider: ^2.0.2
  permission_handler: ^7.1.0
  file_picker: ^3.0.4
Enter fullscreen mode Exit fullscreen mode

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);

  });
}
Enter fullscreen mode Exit fullscreen mode

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;
  });
}
Enter fullscreen mode Exit fullscreen mode

Download Complete code for Flutter CSV File Import

Discussion (0)