gpt4 book ai didi

flutter StreamBuilder 在我运行时显示错误

转载 作者:IT王子 更新时间:2023-10-29 06:52:36 26 4
gpt4 key购买 nike

我正在尝试使用 StreamBuilder 从我的 api 中获取数据,这就是我所做的

 loadProduct(String categoryId, int limit, int offset) async {
fetchProducts(http.Client(), categoryId, limit, offset).then((res) async {
return res;
});
}

static List<Products> parseProducts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Products>((json) => Products.fromJson(json)).toList();
}

Future<List<Products>> fetchProducts(http.Client client, String categoryId, int limit, int offset) async {
final response = await http.post(Configuration.url +
"api/getProducts/" +
categoryId +
"/" +
limit.toString() +
"/" +
offset.toString());
if (response.statusCode < 200 || response.statusCode > 300) {
throw new Exception('Failed to fetch data');
} else {
return compute(parseProducts, response.body);
}
}

下面是我的使用方法

 Flexible(
child: StreamBuilder<List<Products>>(
stream: _productController.stream,
builder: (context, snapshot) {
print(snapshot.connectionState);
if (snapshot.connectionState.toString() ==
"ConnectionState.done") {
if (snapshot.hasError) {
return errMess(context, "Failed to fetch data");
} else {
if (snapshot.hasData) {
if (snapshot.data.length > 0) {
return ProductList(category: snapshot.data);
} else {
return errMess(context,
"There is no available product in this category");
}
} else {
return errMess(context,
"There is no available product in this category");
}
}
} else {
return Center(child: CircularProgressIndicator());
}
},
)),

当我运行它时,我得到了这个错误

I/flutter (26535): Another exception was thrown: type '_ControllerStream<dynamic>' is not a subtype of type 'Stream<List<Products>>'

我的完整代码 https://gist.github.com/bobykurniawan11/6318018d0afc7395213c3e0604d5aab2

我该如何解决?

最佳答案

两件事:

如果您使用流来显示产品列表,您需要将项目添加到该流。

loadProduct(String categoryId, int limit, int offset) async {
List<Product> products = await fetchProducts(http.Client(), categoryId, limit, offset);
_productController.sink.add(products);
}

另一件事是输入您的 StreamController。

  StreamController<List<Product>> _productController = new StreamController<List<Product>>();

PS:额外提示

您可以使用枚举检查相等性(不易出错);)

if (snapshot.connectionState == ConnectionState.done) {

您可以简化构建器函数,因为您实际上并不需要连接状态:

if (snapshot.hasError) {
return errMess(context, "Failed to fetch data");
}else if (snapshot.hasData){
if (snapshot.data.isNotEmpty) {
return ProductList(category: snapshot.data);
} else {
return errMess(context,
"There is no available product in this category");
}
}else{
return Center(child: CircularProgressIndicator());
}

关于flutter StreamBuilder 在我运行时显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57037833/

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