【问题标题】:ERROR:flutter/lib/ui/ui_dart_state.cc(166) Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'错误:flutter/lib/ui/ui_dart_state.cc(166) 未处理的异常:类型“字符串”不是“索引”类型“int”的子类型
【发布时间】:2020-10-03 09:56:07
【问题描述】:

我尝试使用 HTTP URL 从 Flutter Firebase 中获取数据,但发生了此错误。 请帮我解决这个错误。 [错误:flutter/lib/ui/ui_dart_state.cc(166)] 未处理的异常:类型“字符串”不是“索引”类型“int”的子类型 Products.fetchAndSetProducts 谢谢你

Future<void> fetchAndSetProducts([bool filterByUser = false]) async {
  final filterString = filterByUser ? 'orderBy="creatorId"&equalTo="$userId"' :'';
  var url = 'https://cowmilknew.firebaseio.com/products.json?auth=$authToken&$filterString';
  try {
    final response = await http.get(url);
    final extractedData = json.decode(response.body) as Map<String, dynamic>;
    if (extractedData == null) {
      return;
    }
     url =
    'https://cowmilknew.firebaseio.com/RetailerWishlist/$userId.json?auth=$authToken';
    final favoriteResponse = await http.get(url);
    final favoriteData = json.decode(favoriteResponse.body);

    final List<Product> loadedProducts = [];
    extractedData.forEach((prodId, prodData) {
      loadedProducts.add(Product(
        id: prodId,
        title: prodData['title'],
        description: prodData['description'],
        price: prodData['price'],
        isFavorite: favoriteData == null ? false : favoriteData[prodId] ?? false,
        imageUrl: prodData['imageUrl'],
      ));
    });
    _items = loadedProducts;
    notifyListeners();
  } catch (error) {
    throw (error);
  }
}
@override
  void didChangeDependencies() {
    if (_isInit) {
      setState(() {
        _isLoading = true;
      });
      Provider.of<Products>(context,listen: false).fetchAndSetProducts().then((_) {
        setState(() {
          _isLoading = false;
        });
      });
    }
    _isInit = false;
    super.didChangeDependencies();
  }

【问题讨论】:

  • 你在哪一行得到这个错误
  • 检查 id 的变量类型和价格其中之一与 json 数据不匹配。

标签: firebase flutter


【解决方案1】:

我无法准确告诉您错误在哪里,因为您没有提供完整的错误日志,但很明显您正在尝试将 int 传递给字符串,所以我猜测错误可能在于价格: prodData['价格'] 所以这样做将价格转换为int

price: prodData['price'].toString();

【讨论】:

  • 在我写 `double price;` 但现在改为 `int price;` 现在这个错误显示:type 'double' is not a subtype of type 'int'。
  • 当我尝试你的方法时,错误:字符串不能分配给 int。我该如何解决这个问题??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 2021-03-22
  • 1970-01-01
相关资源
最近更新 更多