2

I am trying to read a csv file in flutter and I am getting an error

(OS Error: No such file or directory, errno = 2)

The csv file has been declared in assets section in pubspec.yaml

And the path to the file is correct, here is my attempt to read the file synchronously:

-- at the begining of the class:

List<String> lines;

-- pubspec.yaml, assets section:

assets:
    - assets/videos/
    - assets/images/
    - assets/data/data.csv

-- Method to read file

void _readDataFile(String csvFile) {
    File file = File(csvFile);
    lines = file.readAsLinesSync();
  }

-- Calling the above method ---

@override
  void initState() {
    super.initState();

    //other stuff ...
    // ...
    // ...

    _readDataFile("assets/data/data.csv");
  }
codeKiller
  • 5,493
  • 17
  • 60
  • 115

1 Answers1

1

You can use rootBundle to get the file in asset:

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/data/data.csv');
}

official document link https://flutter.dev/docs/development/ui/assets-and-images#loading-text-assets
similar question Flutter - Read text file from assets

chunhunghan
  • 51,087
  • 5
  • 102
  • 120
  • thanks, i think though, your answer refers to asynchronous read waiting for a Future, while my question talks about a synchronous read, but its a good starting point, thanks! – codeKiller Aug 14 '19 at 06:42