Filter in list with flutter

Asked

Viewed 591 times

0

I need to filter in a list type JSON based on your ID, I am loading the data from the list and then having to filter with Where, but it returns empty even if your ID exists.

The list goes like this:

class Bancos {
  static List<Map> getBancos() {
    List<Map> _myBankJSON = [
      {"id": '1',  "name": "Abc Brasil","image": "assets/bancosimg/abcbrasil.png"},
      {"id": '2',  "name": "Abn Amro", "image": "assets/bancosimg/abnamro.png"},
  
    ];
    return _myBankJSON;
  }
}

and the stare I’m trying to make:

class __BancoFiltradoState extends State<_BancoFiltrado> {
  List<Map> _dadosBanco;
  @override
  void initState() {
    super.initState();
    _dadosBanco = Bancos.getBancos();
   var teste = _dadosBanco.where((element) => element['id'] == 1);
    print(teste.toList());
  }

  @override
  Widget build(BuildContext context) {
    return Container(
    );
  }
}

How can I make this filter?

1 answer

0


The problem is you’re comparing a int with String here:

_dadosBanco.where((element) => element['id'] == 1);

Since the element is a Map<String, String>. Example comparing correctly with String:

void main() {
  final list = <Map>[
      {"id": '1',  "name": "Abc Brasil","image": "assets/bancosimg/abcbrasil.png"},
      {"id": '2',  "name": "Abn Amro", "image": "assets/bancosimg/abnamro.png"},
    ];

  print(list.where((e) => e['id'] == 1));
  print(list.where((e) => e['id'] == '1'));
}

The second where will print the element found. Example running on Dartpad.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.