gpt4 book ai didi

flutter - findById 在热重载时返回 null

转载 作者:行者123 更新时间:2023-12-04 12:54:14 41 4
gpt4 key购买 nike

我有以下 dart 类,它加载一个对象和一个图像。当我执行热重载时,函数 findById 返回错误消息 Bad State: No element .在调试时,我看到我正在查询的列表是空的,一旦我进行了热重播。我想知道为什么会发生这种情况以及如何解决这个问题?

class ProductDetailScreen extends StatefulWidget {
static const routeName = '/product-detail';

@override
_ProductDetailScreenState createState() => _ProductDetailScreenState();
}

class _ProductDetailScreenState extends State<ProductDetailScreen> {
var loadedProduct;
var productId;
var _isLoading;
var _imageUrl;
var cartId;
var imagePath = '';
@override
void initState() {
super.initState();
createCartId();
}

Future<void> createCartId()async {
var id = await nanoid(10);
cartId = id;
}

Future<void> didChangeDependencies() async {
productId = ModalRoute.of(context).settings.arguments as String;
imagePath = productId;
setState(() {
_isLoading = true;
});

final myCacheManager = MyCacheManager();
await myCacheManager.cacheImage(imagePath).then((String imageUrl) {
setState(() {
_imageUrl = imageUrl;
_isLoading = false;
});
});

}
@override
Widget build(BuildContext context) {
loadedProduct = Provider.of<Products>(context,listen:false).findById(productId);
Size size = MediaQuery.of(context).size;
var userId = Provider.of<Auth>(context, listen: false).userId;

return !(_isLoading)?Scaffold(
appBar: AppBar(
actions: null,
title: Text(loadedProduct.title),
),
body:
CustomScrollView(
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child:
Column(
children: <Widget>[
Container(
height: size.height * 0.35,
width: double.infinity,
child:_imageUrl != 'No picture loaded'?
CachedNetworkImage(
imageUrl: _imageUrl,
progressIndicatorBuilder: (context, url, downloadProgress) =>
Center(child:Loading()),
errorWidget: (context, url, error) => Image.asset('assets/images/placeholder.png'),
)
:Image.asset('assets/images/placeholder.png'),
),
Expanded(
child: ItemInfo(
cartId,
loadedProduct.id,
loadedProduct.title,
loadedProduct.price,
loadedProduct.description,
loadedProduct.categoryName,
loadedProduct.isAvailable),
),
],
))]))
:Center(child:Loading());
}
}

class ItemInfo extends StatefulWidget {

ItemInfo(this.cartId,this.id,this.name,this.price,this.description,this.category,this.isAvailable);
var id;
var cartId;
var name;
var price;
var description;
var category;
var isAvailable;

@override
_ItemInfoState createState() => _ItemInfoState();
}

class _ItemInfoState extends State<ItemInfo> {
bool changePrice = false;
List<String> selectedItems;
@override
Widget build(BuildContext context) {
return
Container(
padding: EdgeInsets.all(15),
width: double.infinity,
decoration: BoxDecoration(
boxShadow: [BoxShadow(color: Colors.orange, spreadRadius: 1)],
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
),
child:
Column(
children: <Widget>[
TitlePriceRating(
name: widget.name,
price: widget.price,
),
],
),
);
}
}
这是函数函数 findById
Product findById(String id) {

return _items.firstWhere((prod) => prod.id == id);
}
这是设置 _items 列表的函数:
Future<void> fetchAndSetProducts(String title) async {
var encodedTitle = Uri.encodeComponent(title);
var url = 'https://mm-nn-default-rtdb.firebaseio.com/products.json?auth=$authToken';
try {
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body) as Map<String, dynamic>;
final List<Product> loadedProducts = [];

if (extractedData == null || extractedData['error'] != null) {
_items = loadedProducts;
return _items;
}
extractedData.forEach((prodId, prodData) {
loadedProducts.add(Product(
id: prodId,
title: prodData['title'],
description: prodData['description'],
price: prodData['price'],
categoryName: prodData['categoryName'],
));
});
notifyListeners();
_items = loadedProducts;
return _items;
} catch (error) {
throw (error);
}
}
该函数在名为 ProductOverviewScreen 的类中调用。然后调用一个名为 ProductGrid 的类. ProductGrid基本上包含产品的 ListView 构建器。这个类然后调用 ProductItem这基本上是产品列表中的单个产品。 ProductItem包含一个按钮,单击该按钮时会调用 ProductDetailsScreen这是导致错误的类。

最佳答案

使用 setState 方法。

   Future<void> didChangeDependencies() async {
setState(() {
productId = ModalRoute.of(context).settings.arguments as String;
imagePath = productId;
_isLoading = true;
});

final myCacheManager = MyCacheManager();
await myCacheManager.cacheImage(imagePath).then((String imageUrl) {
setState(() {
_imageUrl = imageUrl;
_isLoading = false;
});
});
}

关于flutter - findById 在热重载时返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68964808/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com