Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

Flutter offline data changes in Hive, ListView UI not updating when data changes

//----- I am trying to refresh UI when product quantity increases or decreases in Hive DB-----//

//---------------My HIVE Class--------------------------//

@HiveType(typeId: 0)
class ProductDBModel extends HiveObject{
  @HiveField(0)
  int id;
  @HiveField(1)
  String productName;
  @HiveField(2)
  String image;
  @HiveField(3)
  int price;
  @HiveField(4)
  String description;
  @HiveField(5)
  int quantity;

  ProductDBModel(this.id, this.productName, this.image, this.price, this.description, this.quantity);
 
}

//-------------------My Cart Class I am using stream builder---------------------------//

class CartScreen extends StatefulWidget {
  @override
  _CartScreenState createState() => _CartScreenState();
}

class _CartScreenState extends State<CartScreen> {
  Future<List> stream;

  @override
  void initState() {
    super.initState();
    stream = _openBoxgetList();
  }

  Future<List<ProductDBModel>> _openBoxgetList() async {
      Box hive_prod_box = await Hive.openBox<ProductDBModel>(ProductTable);
       List rawFavouriteList = await hive_prod_box.values.toList();
       return rawFavouriteList;
  }

  @override
  Widget build(BuildContext context) {  

    return StreamBuilder<List<ProductDBModel>>(
        stream: stream.asStream(),
        builder: (context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return Container(child: Center(child: CircularProgressIndicator()));
          }
          else if(snapshot.hasError){
            return Scaffold(body: Text('Error Occured while loading cart'),);
          }
          else
          {
            if(snapshot.data.length == 0){
              Hive.deleteFromDisk();
              return ShowEmptyCart();
            }
            else{
              return
                Scaffold(                 
                  body: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8.0),
                    child: ListView.builder(
                          physics: ScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: snapshot.data.length,
                          itemBuilder: (context, index) {
                          
                            return Dismissible(
                              background: Container(color: Colors.red),
                              key: UniqueKey(),
                              onDismissed: (direction) {
                                snapshot.data[index].delete();
                              },
                              child: CartItem(snapshot.data[index], index),
                            );
                          },
                        ),
                  ),
                );
            }

          }
        });

  }

}

//------------------cart item class to update product quantity-----------------//

class CartItem extends StatefulWidget {
  ProductDBModel prod_;
  int index;    
  CartItem(ProductDBModel this.prod_, this.index);    
  @override
  _CartItemState createState() => _CartItemState();
}

class _CartItemState extends State<CartItem> {
  CartScreen _cartScreen = new CartScreen();
  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 5.0),
        child: Container(
          height: 150.0,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                    padding: const EdgeInsets.only(left: 10.0),
                    Container(
                          decoration: BoxDecoration(
                            color: grey_background,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceAround,
                            children: [
                              InkWell(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(8.0, 5.0, 8.0, 5.0),
                                  child: TextOnlyFont14(
                                      '-', Colors.black, FontWeight.w600),
                                ),
                                onTap: () {
                                  CheckUpdate(widget.prod_, widget.index, "dec", context);
                                },
                              ),
                              TextOnlyFont14(widget.prod_.quantity.toString(),
                                  Colors.black, FontWeight.w600),
                              InkWell(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(8.0, 5.0, 8.0, 5.0),
                                  child: TextOnlyFont14(
                                      '+', Colors.black, FontWeight.w600),
                                ),
                                onTap: () {
                                  CheckUpdate(widget.prod_, widget.index, "inc", context);
                                },
                              ),
                            ],
                          ),
                        ),
                  ),
              
            ],
          ),
        ),
      ),
    );
  }

  Future<void> CheckUpdate(ProductDBModel product, int index_, String inc_dec,
      BuildContext context) async {
    Box prodBox = await Hive.openBox<ProductDBModel>(ProductTable);

    final modelExists = prodBox.containsKey(product.key);

    if (!modelExists) {
      product.quantity = 1;
      await prodBox.add(product);
    } else {
      if (equalsIgnoreCase(inc_dec, "inc")) {
        product.quantity += 1;
      } else if(equalsIgnoreCase(inc_dec, "dec")) {
        if (product.quantity == 1) {
        } else {
          product.quantity -= 1;
        }
      }
      else if(equalsIgnoreCase(inc_dec, "del")) {
        product.delete();
      }
      product.save();
    }

  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...