sk784
sk784

Reputation: 1

How to convert List<Object> flutter

i'm new in flutter and need to help:

I have already got

final List<Genres> genres = [{1,"comedy"}, {2,"drama"},{3,"horror"}]

from api.

class Genres {

  final int id;
  final String value;

  Genres({this.id,this.value});
}

In another method I get genres.id.(2) How can I convert it to genres.value ("drama")?

Upvotes: 0

Views: 300

Answers (3)

Abion47
Abion47

Reputation: 24661

Getting a Genre from an id is inconvenient when your data structure is a List. You have no choice but to iterate over the list and compare the id value to the id of each element in the list:

final id = 2;
final genre = genres.firstWhere((g) => g.id == id, orElse: () => null);

The problem with this code is that it's slow and there could be multiple matches (where the duplicates after the first found would be ignored).

A better approach would be to convert your list to a Map when you first create it. Afterwards, you can simply use an indexer to get a Genre for an ID quickly and safely.

final genresMap = Map.fromIterable(genres, (item) => item.id, (item) => item);

// later...

final id = 2;
final genre = genresMap[id];

This way, there is guaranteed to not be any duplicates, and if an ID doesn't exist then the indexer will simply return null.

Upvotes: 1

Sebastian
Sebastian

Reputation: 3894

You can find the item inside the List<Genres> like this

Genres element = list.firstWhere((element) => element.id == 2); // 2 being the id you give in the question as an exaple. You should make it dynamic
print(element.value);

Upvotes: 0

Ahmed Khattab
Ahmed Khattab

Reputation: 2799

you could iterate over the json result of the api and map them to the Gener class like so,

void fn(id) {
  final gener = geners.firstWhere((gener) => gener['id'] == id);

  // now you have access to your gener
}

Upvotes: 0

Related Questions