Home > Software design >  Convert CSV to List<List<dynamic>> with rows and columns
Convert CSV to List<List<dynamic>> with rows and columns

Time:10-18

I want to convert csv to List<List> my code bellow is working and get the file and convert it like this: [[item 1;1200;1300],[item 2;1200;1300]].

It's handle [item 1;1200;1300] as a single element I can't reach item 1 or 1200 or 1300 as alone.

I want to handle it like this List[0][0] the result will be item 1.

TextButton(
                onPressed: () async {
                  result = await FilePicker.platform.pickFiles(
                    type: FileType.custom,
                    allowedExtensions: ['csv'],
                    dialogTitle: 'Choose Your File',
                  );
                  if (result != null) {
                    PlatformFile file = result!.files.first;
                    filePath = file.path!;
                    prvdr.openFile(filePath);
                  } else {}
                },
                child: const Text('Press Here'),
              ),

The Fuction

void openFile(filePath) async {
    File itemsFile = File(filePath);
    print('CSV to List');
    final input = itemsFile.openRead();
    final fields = await input.transform(utf8.decoder).transform(const CsvToListConverter()).toList();
    print(fields);
    for(var i = 0; i < fields.length; i  ){
      print(fields[i][0]);
      print(fields[i][1]);
      print(fields[i][2]);
    }
  }

My csv is like this

item 1;1200;1300
item 2;1200;1300
item 3;1200;1300
item 4;1200;1300

CodePudding user response:

You should do a for loop that loops on the list and splits every element by ;

Example:

final fields = await input.transform(utf8.decoder).transform(const CsvToListConverter()).toList();
List<List<String>> finalList = [];

for(var i = 0; i < fields.length; i  ){
  finalList.add(fields[i].split(";"));
}

// Now you cand access finalList
for(var i = 0; i < finalFields.length; i  ){
  print(finalFields[i][0]);
  print(finalFields[i][1]);
  print(finalFields[i][2]);
}

CodePudding user response:

My code is working, I just change the semicolon in csv file into colon. It's working!.

  • Related