Home > database >  'List<dynamic>' is not a subtype of type 'List<String>' when decodin
'List<dynamic>' is not a subtype of type 'List<String>' when decodin

Time:02-12

When I try to get data from my Firebase database I encounter this error when decoding List. This is the error. Unhandled Exception: type 'List' is not a subtype of type 'List'. I attach the method, which triggers the error.

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;  
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'],
            steps: data['steps'],
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }

CodePudding user response:

Attach your Recipe model, for what I can see there is an attribute that is of type List<String> but firebase cast it to List<dynamic>, maybe try to do something like this if you're sure they're all of type String:

Future<void> fetchProducts() async {
    final url = Uri.parse(
        'https://recipier-e1139-default-rtdb.europe-west1.firebasedatabase.app/recipes.json');
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;  
    if (extractedData.isEmpty || extractedData['error'] != null) {
      return;
    }
    List<Recipe> loadedRecipes = [];
    extractedData.forEach(
      (id, data) {
        loadedRecipes.add(
          Recipe(
            title: data['title'],
            description: data['description'],
            id: id,
            ingredients: data['ingredients'].cast<String>(), /// if this is of type list
            steps: data['steps'].cast<String>(), /// if this is of type list
            kcal: data['kcal'],
            p: data['p'],
            c: data['c'],
            f: data['f'],
          ),
        );
      },
    );
    _recipes = loadedRecipes;
    notifyListeners();
  }
  • Related