0

I have a problem getting the List of Strings from the map on the function fromMap. Error: Unhandled Exception: type 'List' is not a subtype of type 'List'

class Ong {
  final String nombre;
  final List<String> PalabrasClave;

  Ong({
    required this.nombre,
    required this.PalabrasClave,
  });

  Map<String, dynamic> toMap() {
    return {
      'Nombre': nombre,
      'Palabras Clave': PalabrasClave,
    };
  }

  factory Ong.fromMap(Map<String, dynamic> map) {
    return Ong(
      nombre: map['Nombre'],
      PalabrasClave: map['Palabras Clave'],
    );
  }

¿How can I solve it?

  • 1
    Hi Diego. Can I assume you are trying to store data locally and you are using toMap and fromMap to write to/ from SQLite? Are you trying to use any SQLite wrappers? like SQFlite or MOOR? If you could include more details of your implementation that would be helpful. I am actually working on the exact same thing right now and I might have some insight – valeriana Jul 27 '21 at 20:29
  • You can cast the getter to a list: map["Palabras Clave"] as List; – MikkelT Jul 27 '21 at 20:32
  • Try map['Palabras Clave'].cast(). More Info: https://stackoverflow.com/questions/49541914/why-an-explicit-cast-function-in-dart-instead-of-as – hnnngwdlch Jul 27 '21 at 20:55
  • Or List.from(map['Palabras Clave']) – hnnngwdlch Jul 27 '21 at 21:02
  • I tried with map['Palabras Clave'].cast() and it perfectly worked. – Diego jiménez Jul 28 '21 at 13:16

1 Answers1

0

This is what I tried doing

void main() {

  final object = Ong(nombre: "Title", palabrasClave: ["Name1", 'Name2', 'Name3']).toMap();
  
  List list = object['Palabras Clave'];
  
  for(String item in list){
    print(item);
  }
  
  //From Map
  Ong ong = Ong.fromMap(object);
  
  List ongList = ong.palabrasClave;
  
  print(ongList);
}


class Ong {
  final String nombre;
  final List<String> palabrasClave;

  Ong({
    required this.nombre,
    required this.palabrasClave,
  });

  Map<String, dynamic> toMap() {
    return {
      'Nombre': nombre,
      'Palabras Clave': palabrasClave,
    };
  }

  factory Ong.fromMap(Map<String, dynamic> map) {
    return Ong(
      nombre: map['Nombre'],
      palabrasClave: map['Palabras Clave'],
    );
  }
  
}

The Result

Object To Map
Name1
Name2
Name3
List from Map: [Name1, Name2, Name3]

This might help.

Benedict
  • 441
  • 4
  • 14