当我运行它时,Flutter StreamBuilder显示错误

时间:2019-07-15 10:27:36

标签: flutter dart

我正在尝试使用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

我该如何解决?

1 个答案:

答案 0 :(得分:2)

2件事:

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

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());
}