在 flutter 中使用 StreamBuilder 显示来自购物车的流

Display stream from cart with StreamBuilder in flutter

我正在尝试构建电子商务应用程序,但在使用购物车功能时遇到了问题。下面的代码是我为应用程序中的所有购物车功能编写的代码。它适用于所有操作,但我不知道如何使用此飞镖并在应用程序中显示它们。我想使用 StreamBuilder 显示数据。

class Item {
final String brand;
final String category;
final int curtime;
final String description;
final String image;
final String name;
final int price;
final int quantity;

Item(
    {this.brand,
    this.category,
    this.curtime,
    this.description,
    this.image,
    this.name,
    this.price,
    this.quantity});
}

class CartItemsBloc {
final cartStreamController = StreamController.broadcast();
double total = 0.0;
Stream get getStream => cartStreamController.stream;

Map<String, Item> items = {};  

void addToCart(String brand, String category, int curtime, String description,
    String image, String name, int price, it) {
  if (items.containsKey(curtime.toString())) {
    items.update(
      curtime.toString(),
      (old) => Item(
          brand: old.brand,
          category: old.category,
          curtime: old.curtime,
          description: old.description,
          image: old.image,
          name: old.name,
          price: old.price,
          quantity: old.quantity + 1),
    );
  } else {
    items.putIfAbsent(
        curtime.toString(),
        () => Item(
              brand: brand,
              category: category,
              curtime: curtime,
              description: description,
              image: image,
              name: name,
              price: price,
              quantity: 1,
            ));
  }

  cartStreamController.sink.add(items.values.toList());
  allItems['cart items'].add(it);
  for (var entry in items.entries) {
    print(entry.key);
    print(entry.value.quantity);
  }
  print(items.values.toList());
}
double calculate() {
  var total = 0.0;
  items.forEach((key, cart) => total += cart.price * cart.quantity);
  return total;
}

void dispose() {
  cartStreamController.close();
}
}

final bloc = CartItemsBloc();

我想使用 StreamBuilder 显示项目地图。有人可以帮忙吗

你可以这样做:

StreamBuilder(
  stream: bloc.getStream,
  initialValue: [] //when nothing is pushed to the stream yes, I assume an empty list
  builder:(context, snapshot){
    if (!snapshot.hasData){
      return Center(child:CircularProgressIndicator());
    }else{
      //your results builder
      //You can find what you pushed in the stream in snapshot.data
    }
  }
)

您可以找到更多信息和示例 in the StreamBuilder documentation

请注意,为了简单起见,我刚刚考虑了 snapshot.hasData,但您可以找到全面的信息,例如 connectionState in the AsyncSnapshot documentation.