问题
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?
回答1:
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()
来源:https://stackoverflow.com/questions/60386200/object-query-and-remove-parentheses-in-dart-flutter