1

I am making a search request on the List with the Provider pattern.

List<Device> _devices = [
    Device(one: 'Apple', two: 'iphone'),
    Device(one: 'Samsung', two: 'Galaxy')
];

And Query is like this

List<Device> queryQuery(String value) {
return _devices
    .where((device) => device.one.toLowerCase().contains(value.toLowerCase()))
    .toList();

the result I expect to get is iphone when I passed the value Apple.

But the result on the screen that I got is [instance of ‘Device’] when I code like this

child: Text('${deviceData.getDevice('Apple')}'

I do know I should be using some kind of key using two... but I have no idea :-(

1
  • 1
    override toString() method for Device object Commented Feb 17, 2020 at 15:28

2 Answers 2

3

You serialized the wrong object.

What you did end-up being similar to:

Text(Device(one: 'Apple', two: 'iphone').toString());

But you don't want to do Device.toString(). What you want instead is to pass Device.two to your Text.

As such your end result is:

Text('${chordData.chordExpand('Apple').two}')
Sign up to request clarification or add additional context in comments.

3 Comments

Like you said, I want to pass Device.two value to Text on the screen. But the query above returns List<Device> value and returns The getter two isn't defined for the class 'List<Device>'. error. The same errror comes when I changed the query type to Text ... The getter two isn't defined for the class 'String
Then do a .map((device) => device.two)
Hello, would you help me solve this issue? stackoverflow.com/questions/60386200/…
1

By the look of [Instance of 'Device'], it seems the function is returning a list so it is a good idea to check if the list is empty or not. if it is not empty, one of the elements is still needed to be selected. I guess it should be Text('${chordData.chordExpand('Apple')[0].two}') in case the list is not empty.

To summarize, use something like this to handle the case when list is empty

// Inside your build method before returning the widget
var l = chordData.chordExpand('Apple'); // Returns a list of devices
String textToWrite; // Here we will store the text that needs to be written
if(l.isEmpty) textToWrite = 'No results'; // If the filter resulted in an empty list
else textToWrite = l[0].two; // l[0] is an instance of a device which has a property called two. You can select any instance from the list provided it exists

return <Your Widget>(
.....
Text(textToWrite),
.....
);

1 Comment

Thanks. it worked when I do .map((device) => device.two). I will add a empty check function in case the list is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.