How I can read content from file line by line in Flutter web

Issue

I need your help with this please, I am uploading a TXT file with plugin file_picker in Flutter WEB and it is works, after that I would like to read the content line by line and process this data, but I dont know to do this…

My code is this:

  //load File from txt
  loadFile() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['txt'],
    );

    if (result != null) {
      PlatformFile file = result.files.first;

      print(file.name);
      // print(file.bytes);
      print(file.size);
      print(file.extension);
      print(file.path);

      print("contenido");

      setState(() {
        _nameFile = file.name;
        _uploadFile = true;
      });
    } 
  }

Someone has any idea to do this?, I was investigating but I did not find much information about it, thnx a lot for that

PD: this project is only works on FLutter Web

Solution

You can convert the file.bytes to a String and then split this String at each line return (\n) the following way:

import 'convert.dart';

String fileContent = utf8.decode(file.bytes);
List<String> lines = fileContent.split('\n');

Answered By – Antonin GAVREL

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *