Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Search elements in array with firstwhere

Tags:

flutter

dart

The problem is simple: What is the correct way to search element in array ?

My code is

data = [{id: 1, descripcion: Asier}, {id: 2, descripcion: Pepe}]
estateSelected= data.firstWhere((dropdown)=>dropdown.id==1);

The error that return is

Bad state: no element

like image 275
El Hombre Sin Nombre Avatar asked Feb 26 '19 16:02

El Hombre Sin Nombre


People also ask

How do you use firstWhere in flutter?

firstWhere method Null safetyReturns the first element that satisfies the given predicate test . Iterates through elements and returns the first to satisfy test . If no element satisfies test , the result of invoking the orElse function is returned. If orElse is omitted, it defaults to throwing a StateError.

How do you get a specific element from a list in Dart?

To get an element at specific index from a List in Dart, call elementAt() method on this list and pass the index as argument. elementAt() method returns the element. If the index is out of range for the list, then elementAt() throws RangeError .


1 Answers

You have some errors, this should work:

  var data = [{'id': 1, 'descripcion': 'Asier'}, {'id': 2, 'descripcion': 'Pepe'}];
  var estateSelected = data.firstWhere((dropdown) => dropdown['id'] == 1);
  print(estateSelected);

Fastest way to try is on dartpad

like image 157
shadowsheep Avatar answered Sep 24 '22 01:09

shadowsheep