Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to sort "This expression has a type of 'void' so its value can't be used."

Tags:

flutter

dart

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.'

like image 463
geezcake Avatar asked Oct 30 '25 17:10

geezcake


2 Answers

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.

like image 100
Dartist Avatar answered Nov 01 '25 14:11

Dartist


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"]));;
like image 31
Sheraz Asghar Avatar answered Nov 01 '25 12:11

Sheraz Asghar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!