I try to do a filter function for a Listview.
Here is the code of the filter function :
void filterSearchResults() {
List<Club> dummySearchList = List<Club>();
dummySearchList.addAll(widget.club);
if(currentEnvironment != '' ) {
List<Club> dummyListData = List<Club>();
dummySearchList.forEach((club) {
if(club.environment == currentEnvironment) {
dummyListData.add(club);
}
});
setState(() {
clubs.clear();
clubs.addAll(dummyListData);
});
return;
} else {
setState(() {
clubs.clear();
clubs.addAll(widget.club);
});
}
}
It's suposed to go through every Club I got, and if the environment of the Club is equal with the value of currentEnvironment
, the club is added to a list for printing them out.
But the if(club.environment == currentEnvironment)
always send me false. if I check both of my values, I found that the string of the current club object is "Mountain" and the currentEnvironment
is "Mountain" too. They both supposed to be of the String type.
With if(club.environment == "Mountain")
it's working as presumed.
I get my clubs with local Json, and the currentEnvironment
is stored in SharedPreferences
Code to get my currentEnvironment
:
class ClubList extends StatefulWidget {
final List<Club> club;
ClubList({Key key, this.club}) : super(key: key);
@override
_ClubListState createState() => _ClubListState();
}
class _ClubListState extends State<ClubList> {
var clubs = List<Club>();
String currentEnvironment;
@override
setData() {
getSelectedEnvironment().then((value) {
setState(() {
currentEnvironment = value;
print("currentEnvironment ${currentEnvironment}");
filterSearchResults();
});
});
}
void initState() {
clubs.addAll(widget.club);
setData();
filterSearchResults();
super.initState();
}
Future<String> getSelectedEnvironment() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString("selectedEnvironment");
}
I don't know if you need other information, tell me if it's the case.
I found the solution to my problem. I just have to call the filterSearchResults()
in my setData()
. Like that, the function wait to have a value to be launched.