gpt4 book ai didi

android - notifyListener 的奇怪行为

转载 作者:IT王子 更新时间:2023-10-29 07:15:13 25 4
gpt4 key购买 nike

我有一个从服务器获取的列表,但是当我们超出获取方法时,列表被初始化为默认值。我注意到问题出在 notifyListeners() 上,如下所示: Does notifyListeners() sometimes complete asynchronously?

有趣的是,在获取方法中列表是可以的。

class Products with ChangeNotifier {

List<Product> _loadedProducts = [];

Future<void> fetchAndSetProducts() async {
try {
var response =
await http.get(StoreServer.serverAddress + '/products.json');

final extractedData = json.decode(response.body) as Map<String, dynamic>;
List<Product> extractedList = [];
extractedData.forEach((key, value) {
_loadedProducts.add(Product(
id: key,
imageUrl: value['imageUrl'],
title: value['title'],
price: value['price'],
description: value['description'],
isFavorite: value['isFavorite']));
});
_loadedProducts = extractedList;
notifyListeners();
await Future.delayed(Duration(seconds: 1));
} catch (error) {
throw error;
}
}

 @override
void didChangeDependencies() {
if (!isInit) {
setState(() {
isLoading = true;
});
test = Provider.of<Products>(context);
test.fetchAndSetProducts().then((_) {
print("fetched");
setState(() {
isLoading = false;
isInit = true;
});
});
}
super.didChangeDependencies();
}

最佳答案

你有一个逻辑错误。检查我的评论..!

class Products with ChangeNotifier {

List<Product> _loadedProducts = [];

Future<void> fetchAndSetProducts() async {
try {
var response =
await http.get(StoreServer.serverAddress + '/products.json');

final extractedData = json.decode(response.body) as Map<String, dynamic>;
List<Product> extractedList = []; // it is an empty list
extractedData.forEach((key, value) {
_loadedProducts.add(Product( // you add elements to _loadedProducts
id: key,
imageUrl: value['imageUrl'],
title: value['title'],
price: value['price'],
description: value['description'],
isFavorite: value['isFavorite']));
});
_loadedProducts = extractedList; // you reassign _loadedProducts to the empty list "extractedList"
notifyListeners();
await Future.delayed(Duration(seconds: 1));
} catch (error) {
throw error;
}
}

我说的对吗?我认为你有那个错误!

关于android - notifyListener 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57594098/

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