Why the function is returning an empty list in Flutter

Issue

So Here’s the code. The error is when calling loadSounds function from outside the class returns an empty list. But when loadSounds is called from loadcategories it works fine and returns a list containing instances of Sound. Even priniting the sounds variable in the loadSounds function prints an empty list.

class AudioRepository {
  List<Category> categories = <Category>[];
  List<Sound> sounds = <Sound>[];

  Future<String> _loadCategoriesAsset() async =>
      await rootBundle.loadString(Assets.soundsJson);

  Future<List<Category>> loadCategories() async {
    if (categories.isNotEmpty) {
      return categories;
    }

    String jsonString = await _loadCategoriesAsset();
    categories.clear();
    categories.addAll(categoryFromJson(jsonString));
    categories.map((c) => sounds.addAll(c.sounds)).toList();
  
    loadSounds('1');
    return categories;
  }

  Future<List<Sound>> loadSounds(String categoryId) async {
    print(sounds);
    return sounds
        .where((sound) => sound.id.substring(0, 1) == categoryId)
        .toList();
  }
}

Output when called from loadCategories is as follows:

[Instance of 'Sound', Instance of 'Sound', Instance of 'Sound', Instance of 'Sound', Instance of 'Sound', Instance of 'Sound']

I’m accessing it outside the class as follows:

final _sounds = await repository.loadSounds(event.categoryId);

Output when called from outside or printing from loadSounds function is as follows:

[]

So what’s the problem here. I’m not able to figure out why the loadSounds fuction work when called from loadCategories inside the class and not otherwise in any way.

Solution

If you don’t call repository.loadCategories() before calling loadSounds(), you won’t have anything in your sounds variable since you are assigning values only in your loadCateogries() function.

Is your repository variable a singleton and did you call loadCategories on it?

Also, I would not write this line like this :

categories.map((c) => sounds.addAll(c.sounds)).toList();

The toList() method is not really usefull and the map function should be used more to convert something (a String to Int mapping for instance).

I would use :

categories.forEach((c)=> sounds.addAll(c.sounds));

Answered By – leb1755

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *