我运行时遇到此错误:
[错误:flutter/runtime/dart_vm_initializer.cc(41)] 未处理的异常:类型“String”不是“index”#0 的“int”类型的子类型
Products.fetchAndSetProducts(包:my_shop/providers/products.dart:60:7)
我认为 Firebase 数据库一定有问题。
这是我的 products.dart 代码
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:my_shop/providers/product.dart';
class Products with ChangeNotifier {
List<Product> _items = [];
final String authToken;
final String userId;
Products(this.authToken, this.userId, this._items);
//var _showFavoritesOnly = false;
List<Product> get items {
// if (_showFavoritesOnly) {
// return _items.where((prodItem) => prodItem.isFavorite).toList();
// }
return [..._items];
}
List<Product> get favoriteItems {
return _items.where((prodItem) => prodItem.isFavorite).toList();
}
Product findById(String id) {
return _items.firstWhere((prod) => prod.id == id);
}
Future<void> fetchAndSetProducts([bool filterByUser = false]) async {
final filterString =
filterByUser ? 'orderBy="creatorId"&equalTo="userId"' : '';
var url = Uri.parse(
'https://flutter-update-ced0c-default-rtdb.europe-west1.firebasedatabase.app/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 = Uri.parse(
'https://flutter-update-ced0c-default-rtdb.europe-west1.firebasedatabase.app/userFavorites/$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);
}
}
Future<void> addProduct(Product product) async {
var url = Uri.parse(
'https://flutter-update-ced0c-default-rtdb.europe-west1.firebasedatabase.app/products.json?auth=$authToken');
try {
final response = await http.post(
url,
body: json.encode({
'title': product.title,
'description': product.description,
'price': product.price,
'creatorId': userId,
'imageUrl': product.imageUrl,
}),
);
final newProduct = Product(
id: json.decode(response.body)['name'],
title: product.title,
description: product.description,
price: product.price,
imageUrl: product.imageUrl);
_items.add(newProduct);
//_items.insert(0,newProduct);
notifyListeners();
} catch (error) {
throw (error);
}
}
Future<void> updateProduct(String id, Product newProduct) async {
final prodcutIndex = _items.indexWhere((prod) => prod.id == id);
if (prodcutIndex >= 0) {
var url = Uri.parse(
'https://flutter-update-ced0c-default-rtdb.europe-west1.firebasedatabase.app/products/$id.json?auth=$authToken');
await http.patch(
url,
body: json.encode({
'title': newProduct.title,
'description': newProduct.description,
'price': newProduct.price,
'imageUrl': newProduct.imageUrl,
}),
);
_items[prodcutIndex] = newProduct;
notifyListeners();
} else {
print('...');
}
}
Future<void> deleteProduct(String id) async {
var url = Uri.parse(
'https://flutter-update-ced0c-default-rtdb.europe-west1.firebasedatabase.app/products/$id.json?auth=$authToken');
final existingProductIndex = _items.indexWhere((prod) => prod.id == id);
Product? existingProduct = _items[existingProductIndex];
_items.removeAt(existingProductIndex);
notifyListeners();
final response = await http.delete(url);
if (response.statusCode >= 400) {
_items.insert(existingProductIndex, existingProduct);
notifyListeners();
throw const HttpException('Could not delete the product!');
}
existingProduct = null;
}
}
您提供的代码片段似乎正在将产品添加到名为
loadedProducts
的列表中。该错误可能与您处理价格数据的方式有关(prodData['price'])
。确保 prodData['price']
确实返回一个整数值,因为它似乎在代码中的某处被视为字符串。
以下是处理此问题的方法:
price
地图中的 prodData
字段存储为整数。price
存储为字符串,则需要先将其转换为整数,然后再将其分配给 price
的 Product
属性。以下是如何将价格转换为整数的示例:
price: int.parse(prodData['price']),
此行会将
prodData['price']
的字符串值解析为整数。确保 prodData['price']
始终包含有效的整数表示形式,否则,您可能会遇到解析错误。