Отображение потока из корзины с StreamBuilder во флаттере - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь создать приложение электронной коммерции, но у меня возникают трудности с функцией корзины. Код ниже - это то, что я написал для всех функций корзины в приложении. Он отлично работает со всеми операциями, но я не знаю, как использовать этот дротик и показать их в приложении. Я хочу показать данные с помощью 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. Кто-нибудь, пожалуйста, помогите.

1 Ответ

0 голосов
/ 17 июня 2020

Вы можете сделать что-то вроде этого:

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

Дополнительную информацию и пример можно найти в документации StreamBuilder .

Обратите внимание, что я только что сделал Обратите внимание на snapshot.hasData, чтобы упростить его, но вы можете найти исчерпывающую информацию, такую ​​как connectionState , в документации AsyncSnapshot .

...