Flutter StreamBuilder 错误

Posted

技术标签:

【中文标题】Flutter StreamBuilder 错误【英文标题】:Flutter StreamBuilder errors 【发布时间】:2021-11-14 07:12:35 【问题描述】:

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

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();
    );
  

【问题讨论】:

如何将商品添加到购物车? 【参考方案1】:
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,)
        ],
      )
    );
  

【讨论】:

同样的错误,同样的行为 查看官方文档能否给我发一份完整的代码

以上是关于Flutter StreamBuilder 错误的主要内容,如果未能解决你的问题,请参考以下文章

Flutter 在使用 StreamBuilder 从 firebase 加载数据之前显示红色错误屏幕,如何解决?

Flutter Bloc A 在 Bloc B 中添加流,但此流不会通过 StreamBuilder 在 UI 中呈现

Flutter:从子 StreamBuilder 更新有状态小部件

Flutter Firestore 和 StreamBuilder

如何在 Flutter 的 StreamBuilder 中使用 Future [重复]

从 StreamBuilder BloC firestore Flutter 获取数据时出错