Reputation: 75
im new to flutter, im unable to sort List and get the 'This expression has a type of 'void' so its value can't be used.' error
List getSnack = [];
var sortSnack = [];
Future _getSnacks() async {
var response = await http.get(Uri.parse(url));
List decode = jsonDecode(response.body);
setState(() {
getSnack = decode
.where((snack) => snack["snack_type"]
.toLowerCase()
.contains(defaultType.toLowerCase()))
.toList();
});
sortSnack = getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));
}
i want to sort the "snack" which contains the name of the snack from a-z and vice versa
i have tried this and still doesn't work
List getSnack = [];
var sortSnack = getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));;
Future _getSnacks() async {
var response = await http.get(Uri.parse(url));
List decode = jsonDecode(response.body);
// List filter = decode;
setState(() {
getSnack = decode
.where((snack) => snack["snack_type"]
.toLowerCase()
.contains(defaultType.toLowerCase()))
.toList();
});
}
the error says 'The instance member 'getSnack' can't be accessed in an initializer.'
Upvotes: 4
Views: 3263
Reputation: 37
This is a void function you can't use it or assign it to another variable. you just have to use this as an expression and use your original List after applying sort function.
Remove the commented part and just apply the function which is void.your original list (getSnack) will be updated itself.
//var sortSnack = ...
getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));;
Upvotes: 1
Reputation: 507
Sort() apply its sorting to the list, it's not returning any value (void). What you should write instead is:
getSnack.sort((a, b) => a["snack"].compareTo(b["snack"]));
var sortSnack = getSnack;
or use the cascade operator if you want this on one line:
var sortSnack = getSnack..sort((a, b) => a["snack"].compareTo(b["snack"]));
Be aware that in both cases sortSnack will be a shallow copy of getSnack. Any change in SortSnack will be reflected in getSnack.
Upvotes: 8