No such file when reading CSV file in Flutter

1,281

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

Share:
1,281
codeKiller
Author by

codeKiller

Updated on December 13, 2022

Comments

  • codeKiller
    codeKiller 11 months

    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
    codeKiller about 4 years
    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!