简体   繁体   中英

object query and remove parentheses in dart, flutter

Hello? I'm building an app using the flutter provider pattern. And I created a process to query the values ​​inside the object. I also have data in my model dart file.

Check the code below.

List<Device> _devices = [
    Device(one: 'apple', two: 'iphone'),
    Device(one: 'samsung', two: 'galaxy')
];


String Query(String value) {
    return _media.where((medium) => medium.one == value)
                    .map((medium) => (medium.two)).toString();

Query("apple")

So, when I call that function, I expect iphone to be returned. But the results come in (iphne) . Actually I know why. After all, the data returned is a List<Device> type. But what I want is to remove the parentheses by returning only the first value in the queried list(meaning only queried list, not the full list). In other words, I want to receive iphone , not (iphone) . Currently, I am using substring removing the first and the final word, which seems to have some limitations. Is there any way to remove parentheses in that logic?

You have parentheses because you're calling .toString() on a list:

return _media.where((medium) => medium.one == value)
  .map((medium) => (medium.two))
  .toString();

To return just .two or the first found object, you just have to do:

return _media.firstWhere(
  (medium) => medium.one == value, orElse: () => null)?.two;

That will return the value of .two of the first found object or null if nothing found.

Doc: Iterable.firstWhere()

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