Flutter- CSV file to Map

Viewed 252

I need to convert a CSV file to a Map<String, String> and I'm using this package for the task. The problem is that the output of the map is returning a space before every key, as you can see:

{ 001: Visto de Trabalho,  002: Carta de Pesados,  003: Medicina do Trabalho,  004: Título de Residente]}

This is my code:

HashMap _refHashMap;

Future<HashMap> convertCSV() async {
  _refHashMap = await CSV_HashMap().hashMapConvertor(
      refList: ["id", "name"], csvPath: 'assets/document_types.csv');

  return _refHashMap;
}

Map<String, String> loadDocTypes() {
  convertCSV();

  var ids = _refHashMap["id"];
  var names = _refHashMap["name"];

  var map = Map.fromIterables(ids, names);

  var convertedMap = Map<String, String>.from(map);

  return convertedMap;
}

Can you help me? Thank you in advance

2 Answers

Give this a try, it trims the keys to remove the whitespace at the end.

Map<String, String> loadDocTypes() {
  convertCSV();

  var ids = _refHashMap["id"];
  var names = _refHashMap["name"];

  var map = Map.fromIterables(ids, names);

  var convertedMap = Map<String, String>.from(map);

  return convertedMap.map((key, value) => MapEntry(key.trim(), value)); // Add this line
}

It can be done in such a simple way.
Not very elegant, but this will work as long as the CSV file is as expected by this algorithm (header and records).

import 'package:fast_csv/fast_csv.dart' as _fast_csv;

void main(List<String> args) {
  final data = _fast_csv.parse(_source);
  final keys = data.first;
  final list = data.skip(1).map((e) => Map.fromIterables(keys, e)).toList();
  print(list.first);
  print(list[1]['Name']);
}

const _source = '''
Name,Total Cores,Processor Base Frequency
"Intel® Celeron® Processor G530 2M Cache, 2.40 GHz",2,2.40 GHz
"Intel® Core™ i5-3470 Processor 6M Cache, up to 3.60 GHz",4,3.20 GHz
"Intel® Core™ i3-10100F Processor 6M Cache, up to 4.30 GHz",4,3.60 GHz
''';

Output:

{Name: Intel® Celeron® Processor G530 2M Cache, 2.40 GHz, Total Cores: 2, Processor Base Frequency: 2.40 GHz} Intel® Core™ i5-3470 Processor 6M Cache, up to 3.60 GHz
Related