I'm trying to show a list of search results. The error is with the ListView Builder.
ListView.builder(
itemCount: searchResults.length,
itemBuilder: (context, index) {
final searchResultAccount = searchResults[index];
for (var element in searchResults[index].profile!) {
final searchResultProfile = element;
return ListTile(
leading: CircleAvatar(
backgroundImage: searchResultProfile.profileImage.isNotEmpty
? NetworkImage(
searchResultProfile.profileImage,
)
: null,
child: searchResultProfile.profileImage.isNotEmpty
? null
: const Icon(
Icons.person,
),
),
title: Text(
searchResultProfile.profileName,
),
onTap: () {
//navigate to profile
},
);
}
if (searchResults.isEmpty) {
return Text('no results');
}
},
),
I tried putting the code inside a try-catch block and even with the conditional statement above that I added in the end to return Text widget I'm still getting the same error.
How to clear this error?
CodePudding user response:
It is possible that we will get null value from searchResultAccount
. Therefore, loop may not return any ListTile
widget.
Also, while using loop, it will return a list of widget. But you are returning single ListTile
. You can wrap with Column
.
searchResults.isEmpty
may not meet the criteria and won't return Text(..)
. You can include an else statement and return a widget.
itemBuilder: (context, index) {
final searchResultAccount =....;
List<Widget> xWidgets = [];
for (var element in searchResults[index].profile!) {
xWidgets.add( ListTile(..));
}
if (xWidgets.isNotEmpty) {
return Column(
mainAxisSize: MainAxisSize.min,
children: widgetsX,
);
}
return Text('no results');
},
CodePudding user response:
I would say that one of the parameters are being sent as null, try dugguing to find out where it is sending the error.
Also the for seem a bit inappropriate as it will only iterate once and return the first element of the profile at that index. You can achieve the same getting the first element.