dart Flutter StreamBuilder错误

juud5qan  于 2023-06-03  发布在  Flutter
关注(0)|答案(2)|浏览(222)

实现了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();
    });
  }
wztqucjr

wztqucjr1#

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,)
        ],
      )
    );
  }
}
8zzbczxx

8zzbczxx2#

将StreamBuilder Package 在扩展的小部件中

相关问题