简体   繁体   中英

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")?

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.

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
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM