Search code examples
flutterdart

Flutter- CSV file to Map


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


Solution

  • 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
    }