Flutter Firestore StreamBuilder 最初获得空值

Posted

技术标签:

【中文标题】Flutter Firestore StreamBuilder 最初获得空值【英文标题】:Flutter Firestore StreamBuilder getting null value initially 【发布时间】:2020-01-04 22:41:23 【问题描述】:

我正在尝试使用流构建器方法从 Firestore 获取数据。最初,当我运行应用程序时,我没有从 firebase 获得任何数据。我越来越 Invalid value: Valid value range is empty: 0。 一旦我重新加载应用程序,数据就可用 请在下面找到代码

Widget build(BuildContext context) 
    return StreamBuilder(
        stream: Firestore.instance
            .collection('users/')
            .where('uid', isEqualTo: _userUID)
            .snapshots(),
        builder: (BuildContext context, userSnapshot) 
          if (!userSnapshot.hasData) return WidgetFunctions().loadingWidget();
          return StreamBuilder(
              stream: Firestore.instance
                  .collection('products')
                  .where('latest', isEqualTo: true)
                  .snapshots(),
              builder: (cuserSnapshotontext, snapshot) 
                if (!snapshot.hasData) return WidgetFunctions().loadingWidget();
                if (snapshot.data.documents.length == 0)
                  return const Center(
                    child: Text(
                      "Not Available",
                      style: TextStyle(fontSize: 30.0, color: Colors.grey),
                    ),
                  );

                if (!userSnapshot.data.documents[0]['productViewPermission']) 
                  print('place6');
                  return const Center(
                      child: Text(
                    'You dont have permission to view products \n please contect us',
                    style: TextStyle(
                        fontSize: 18.0,
                        color: Colors.red,
                        fontWeight: FontWeight.bold),
                  ));
                
                return GridView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  itemCount: snapshot.data.documents.length,
                  gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                  ),
                  itemBuilder: (BuildContext context, int index) 
                    return SingleProduct(
                        productCatagory: snapshot.data.documents[index]
                            ['productCatogary'],
                        productName: snapshot.data.documents[index]
                            ['productName'],
                        imageURL: snapshot.data.documents[index]['imageURLS']
                            [0],
                        price: userSnapshot.data.documents[0]
                                ['priceViewpermission']
                            ? snapshot.data.documents[index]['price'].toDouble()
                            : "To view price please contect us",
                        discountBool: snapshot.data.documents[index]
                            ['discount'],
                        discountValue: snapshot.data.documents[index]
                            ['discountValue'],
                        index: index,
                        description: snapshot.data.documents[index]
                            ['description'],
                        make: snapshot.data.documents[index]['make'],
                        karat: snapshot.data.documents[index]['karat'],
                        waight:
                            snapshot.data.documents[index]['waight'].toDouble(),
                        condition: snapshot.data.documents[index]['condition'],
                        populer: snapshot.data.documents[index]['populer'],
                        isAvailable: snapshot.data.documents[index]
                            ['isAvailable']);
                  ,
                );
              );
        );
  

I/flutter ( 3686): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 3686): The following RangeError was thrown building StreamBuilder<QuerySnapshot>(dirty, state:
I/flutter ( 3686): _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#02fde):
I/flutter ( 3686): RangeError (index): Invalid value: Valid value range is empty: 0
I/flutter ( 3686): When the exception was thrown, this was the stack:
I/flutter ( 3686): #0      List.[] (dart:core-patch/growable_array.dart:145:60)
I/flutter ( 3686): #1      _PopularProductsContainerState.build.<anonymous closure>.<anonymous closure> (package:thaya_factory/Components/HomePageComponents/CategoryComponent/LatestProductsComponent.dart:54:49)
I/flutter ( 3686): #2      StreamBuilder.build (package:flutter/src/widgets/async.dart:425:74)
I/flutter ( 3686): #3      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 3686): #4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4012:27)
I/flutter ( 3686): #5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3924:15)
I/flutter ( 3686): #6      Element.rebuild (package:flutter/src/widgets/framework.dart:3721:5)
I/flutter ( 3686): #7      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2340:33)
I/flutter ( 3686): #8      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter ( 3686): #9      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:285:5)
I/flutter ( 3686): #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1016:15)
I/flutter ( 3686): #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:958:9)
I/flutter ( 3686): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:874:5)
I/flutter ( 3686): #16     _invoke (dart:ui/hooks.dart:236:10)
I/flutter ( 3686): #17     _drawFrame (dart:ui/hooks.dart:194:3)
I/flutter ( 3686): (elided 3 frames from package dart:async)
I/flutter ( 3686): ═══════════════════════

请帮我解决问题 在此先感谢

【问题讨论】:

【参考方案1】:

首先,这段代码的语法无效:

if (snapshot.data.documents.length == 0)
  return const Center(
    child: Text(
      "Not Available",
      style: TextStyle(fontSize: 30.0, color: Colors.grey),
    ),
  );

您忘记了 if 语句中的左括号和右括号。

其次,在第二个 if 语句中尝试 else if,因为现在,当 snapshot.data.documents.length 返回 null 时,它仍然会检查 !userSnapshot.data.documents[0],尽管列表是空的,这是导致您的RangeError.

所以试试这个:

if (snapshot.data.documents.length == 0) 
  return const Center(
    child: Text(
      "Not Available",
      style: TextStyle(fontSize: 30.0, color: Colors.grey),
    ),
  );
 else if (!userSnapshot.data.documents[0]['productViewPermission']) 
  print('place6');
  return const Center(
    child: Text(
      'You dont have permission to view products \n please contect us',
      style: TextStyle(
        fontSize: 18.0,
        color: Colors.red,
        fontWeight: FontWeight.bold),
      )
    );

【讨论】:

感谢您的回复,我已经尝试过,但我仍然遇到同样的错误,注意**当我重新加载应用程序时它工作正常。该错误仅在首次启动时发生【参考方案2】:

这是因为 GridView 的 itemCount 没有访问数据快照。

尝试做

itemCount = snapshot.data== null ? 0 : 快照.data.documents.length;

【讨论】:

以上是关于Flutter Firestore StreamBuilder 最初获得空值的主要内容,如果未能解决你的问题,请参考以下文章

从 Flutter 移动应用程序调用 Firestore 是不是安全?

无法从 Firestore 文档中删除字段 (Flutter)

Firestore,Flutter,Async:方法不等待异步方法完成

Flutter/cloud-firestore“任务已经完成”异常

Flutter - 任务':cloud_firestore:compileDebugJavaWithJavac'的执行失败

Flutter web无法从firestore获取数据