簡體   English   中英

Flutter Firebase 讀取數據錯誤:類型“列表”<dynamic> ' 不是類型 'Map 的子類型<string, dynamic> ' 在類型轉換中</string,></dynamic>

[英]Flutter Firebase error in read data: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' in type cast

在此處輸入圖像描述 錯誤:發生異常。 _CastError(類型 'List' 不是類型轉換中類型 'Map<String, dynamic>' 的子類型)

我怎么解決這個問題??

編輯:'extractedData' 是 Map,我如何將其轉換為 List 以將其添加到 'final List loadedProducts = [];' 中?

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/foundation.dart';

class ProductMain with ChangeNotifier{
  final String idFood;
  final String nameFood;
  // ignore: non_constant_identifier_names
  final String ImgUrl;

  ProductMain({
    @required this.idFood,
    this.nameFood,
    // ignore: non_constant_identifier_names
    this.ImgUrl,
  });
}

對於所需的帖子:“看起來您的帖子主要是代碼;請添加更多詳細信息。” “看起來你的帖子主要是代碼;請添加更多細節。”

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:app/product_main_data.dart';

import 'package:http/http.dart' as http;

class ProductsMainPV with ChangeNotifier {
  List<ProductMain> _items = [];

  List<ProductMain> get items {
    return [..._items];
  }

  ProductMain findById(String idFood) {
    return _items.firstWhere((prod) => prod.idFood == idFood);
  }



  Future<void> fetchAndSetProducts() async {
    const url =
        'https://app.firebaseio.com/productList.json';
    try {
      final response = await http.get(url);
      final extractedData = json.decode(response.body);
      final List<ProductMain> loadedProducts = [];
      extractedData.forEach((product) {
        print(product);
        loadedProducts.add(ProductMain(
          idFood: product,
          nameFood: product['nameFood'],
          ImgUrl: product['ImgUrl'],
        ));
      });
      _items = loadedProducts;
      notifyListeners();
    } catch (error) {
      throw (error);
    }
  }

  void updateProduct(String id, ProductMain newProduct) {
    final prodIndex = _items.indexWhere((prod) => prod.idFood == id);
    if (prodIndex >= 0) {
      _items[prodIndex] = newProduct;
      notifyListeners();
    } else {
      print('...');
    }
  }
}

Output:

product is null

我不確定這一點,因為您的問題不包含收到的響應結構。 但是試試這個。

final extractedData = json.decode(response.body) as Map<String, dynamic>;

由於您要列出所有產品,因此它可能是項目列表。 所以將其轉換為 Map 是行不通的!

final extractedData = json.decode(response.body);
......
extractedData.forEach((product) {
   print(product);
   // Do Something!
}

看起來您的 response.body 是 List 而不是 Map。 您期望 url 調用返回什么? 您可以在處理之前使用例如測試它。 If (response.body is Map)...else if (response.body is List)... 如果是 Map,則將其處理為 Map,否則將其處理為 List。

根據評論更新這是地圖列表。 因此,您需要遍歷列表並處理每個 map,可能會遍歷每個 map。 因此需要幾個 for-in 或 for-each 循環。 根據另一個答案,打印出每次迭代以查看您擁有的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM