0

实现了 StreamBuilder 以在购物车的更新价格中显示商品。当购物车中有一个或两个项目时,一切都按预期工作,但是当添加第三个项目时,我正确地获得了第三个项目,但购物车中的第一个和第二个项目显示以下错误:“状态不佳:DocumentSnapshotPlatform 中不存在字段。相关错误-导致小部件是 StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>"。我相信这是一个计时错误(异步/等待),或者需要某种暂停。这是我的代码:

class PriceUpdaterWidget extends StatelessWidget {
  const PriceUpdaterWidget({
    Key? key,
    required this.loginService,
    required this.code,
  }) : super(key: key);

  final LoginService loginService;
  final String? code;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
        stream: FirebaseFirestore.instance
            .collection('shoppers')
            .doc(loginService.loggedInUserModel!.uid)
            .collection("cartItems")
            .doc(code)
            .snapshots(),
        builder: (BuildContext context,
            AsyncSnapshot<DocumentSnapshot<Map<String, dynamic>>> snapshot) {
          SellerNameService isSellerName =
              Provider.of<SellerNameService>(context, listen: false);

          var sellerName = isSellerName.isSellerName;

          final snapshotData = snapshot.data;

          if (snapshot.hasData) {
            return Text(
              snapshot.data![sellerName].toStringAsFixed(2),
              textAlign: TextAlign.center,
            );
          } else {
            return Text('No Datos');
          }
        });
  }
}

购物车中包含一件、两件和三件商品的行为

编辑:物品添加到购物车:

void add(BuildContext context, CartItem item) async {
    _items.add(item);
    int indexOfSeller = await getValue() ?? "";

    LoginService loginService =
        Provider.of<LoginService>(context, listen: false);

    Map<String, dynamic> cartMap = Map();
    var price = item.subCategory!.price as double;
    var isSelectedPrice = item.isSelectedPrice;
    var sellerName = item.subCategory!.parts[indexOfSeller].name;
    var codeTest = item.subCategory!.code!;
    var amount = item.subCategory!.amount;

    _items.forEach((CartItem item) {
      cartMap[item.subCategory!.code!] =
          (item.subCategory as SubCategory).amount;
      //
      cartMap[item.subCategory!.parts[indexOfSeller].name] =
          (item.subCategory!).parts[indexOfSeller].price;
    });

    _instance = FirebaseFirestore.instance;

    _instance!
        .collection('shoppers')
        .doc(loginService.loggedInUserModel!.uid)
        .collection("cartItems")
        .doc(codeTest)
        .set({codeTest: amount, sellerName: price},
            SetOptions(merge: false)).then((codeTest) {
      notifyListeners();
    });
  }
4

1 回答 1

0
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:new_app/custom/action_bar.dart';
import 'package:new_app/custom/constants.dart';
import 'package:new_app/custom/custom_btn.dart';
import 'package:new_app/users/HomePage.dart';

 class NewsView extends StatefulWidget {
   final String newsid;
  NewsView({required this.newsid});
 
   @override
   _NewsViewState createState() => _NewsViewState();
 }
 
 class _NewsViewState extends State<NewsView> {
    final CollectionReference _productsRef= 
 FirebaseFirestore.instance.collection("SportsNews");
   @override
   Widget build(BuildContext context) {
     return Scaffold(
      body: Stack(
        children: [
        FutureBuilder(
          future: _productsRef.doc(widget.newsid).get(),
          builder:(context, AsyncSnapshot<DocumentSnapshot> snapshot){
              if (snapshot.hasError) {
                return Scaffold(
                  body: Center(
                    child: Text("Error: ${snapshot.error}"),
                  ),
                );
              }
              // get data
              if(snapshot.connectionState==ConnectionState.done){
                  DocumentSnapshot<Object?> documentData = snapshot.data!;
                  // list
              
              
                  return Container(
                     
                    
                    child: ListView(
                      children: [
                        Container(
                        
                          // height:390,
                         
                          
                            child:
                            
                             Padding(
                               padding: const EdgeInsets.all(10.0),
                               child: Container(
                                 margin: EdgeInsets.only(top:50,bottom:5),
                                 height:260,
                                 
                                 child: PageView(
                                   children:[
                                    
                                     Container(
                                       
                                       child: ClipRRect(
                                          borderRadius: BorderRadius.circular(18.0),
                                         child: Image.network(
                                                                      (documentData['images']),
                                                                        fit:BoxFit.fill,
                                                                 ),
                                       ),
                                     ),
                                                            
                                                             
                                   ]
                                 ),
                               ),
                             ),
                          
                        ),
                       
                       Padding(
                          padding: const EdgeInsets.symmetric(
                            vertical: 0.8,
                            horizontal: 20.0
                          ),
                          child: Text("${documentData['Category']}",textAlign:TextAlign.right,style: Constants.smallText,),
                        ),
                        Padding(
                          padding: const EdgeInsets.symmetric(
                            vertical: 0.8,
                            horizontal: 20.0
                          ),
                          child: Text("${documentData['Heading']}",textAlign:TextAlign.justify,style: Constants.boldHeading,),
                        ),
                          Padding(
                          padding: const EdgeInsets.symmetric(
                            vertical:10.0,
                            horizontal: 20.0
                          ),
                          child: Text("${documentData['Subheading']}",textAlign:TextAlign.justify,style: Constants.regularHeading,),
                        ),
Padding(
                               padding: const EdgeInsets.all(10.0),
                               child: Container(
                                 margin: EdgeInsets.only(top:5,bottom:5),
                                 height:250,
child: ClipRRect(
  borderRadius: BorderRadius.circular(18.0),
  child:   Image.network(
  
   (documentData['images']),
  
   fit: BoxFit.fill,
  
  ),
),

                               ),),
                        Padding(
                          padding: const EdgeInsets.symmetric(
                            vertical: 0.10,
                            horizontal: 20.0
                          ),
                          child: Text("${documentData['desc']}",textAlign:TextAlign.justify,style: Constants.darkText,),
                        ),
                        Padding(
                               padding: const EdgeInsets.all(10.0),
                               child: Container(
                                 margin: EdgeInsets.only(top:5,bottom:5),
                                 height:250,
child: ClipRRect(
  borderRadius: BorderRadius.circular(18.0),
  child:   Image.network(
  
   (documentData['images']),
  
   fit: BoxFit.fill,
  
  ),
),

                               ),),
                         Padding(
                          padding: const EdgeInsets.symmetric(
                            vertical: 0.10,
                            horizontal: 20.0
                          ),
                          child: Text("${documentData['Subdesc']}",textAlign:TextAlign.justify,style: Constants.darkText,),
                        ),
                        
                         Custombtn(text: "Back",
                            outlinebtn: true, 
                            onPressed:(){
                             Navigator.push(context,MaterialPageRoute(builder: (context)=>HomePage()));
                           },
                            isLoading: false)
                      ],


                      
                    ),
                  );

              }

// loding is true
               return Scaffold(
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
          }),
ActionBar(
  hasBackArrow: true,
   title: "", 
   hastitle:false, 
   hasBackGround:false,)
        ],
      )
    );
  }
}
于 2021-09-20T17:16:15.690 回答