0

伙计们,我是新来的,并且一直在尝试从 firebase 检索数据并使用 streambuilder 将其显示在 gridview 中。但它的快照是空的。我经历了其他用户提出的类似问题,但没有任何效果。

错误:════════(3)widgets库捕获的异常═══════════════════════════════ ═══════════════════ getter 'itemImage' 在 null 上调用。Receiver: null 尝试调用:itemImage 相关的导致错误的小部件是:GridCard file:///C:/Users/dell/foodie_demo/lib/User_Screens/home.dart:107:28 ═════════ ══════════════════════════════════════════════════ ═════════════════════════════════════════

'''
home.dart

import 'package:flutter/material.dart';
import 'package:foodie_demo/Controller/auth.dart';
import 'package:foodie_demo/Model/item_model_pojo.dart';
import 'package:foodie_demo/Sub_widgets/drawer.dart';
import 'package:foodie_demo/Sub_widgets/gridView_card.dart';
import 'package:foodie_demo/User_Screens/item_click.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

class Home extends StatefulWidget {
  final VoidCallback onSignedOutHome;
  final BaseAuth auth;

  Home({this.auth, this.onSignedOutHome});

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String email;
  List <ItemModel> items =[];



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        //TODO: try adding an icon like spoon instead of text here
        title: Icon(
          Icons.star,
        ),

        //ADD FAV AND NOTIFICATIONS ICON (USE STACK FOR NOTIFY)
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.favorite,
            ),
            onPressed: null,
          ),
          Stack(
            //ALIGNMENT IS IMPORTANT FOR NOTIFICATION ICON
            alignment: Alignment.centerLeft,
            children: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.notifications,
                ),
                onPressed: null,
              ),
              CircleAvatar(
                radius: 10.0,
                child: Text('0'),
              )
            ],
          )
        ],
      ),

      //DRAWER WIDGET ADDED FROM drawer.dart(Sub_widgets pkg)
      drawer: DrawerMenu(
          auth: widget.auth,
          signOutSelected: () {
            widget.onSignedOutHome();
          }),

      //ADD GRID VIEW IN BODY
      body: StreamBuilder<QuerySnapshot> (
          stream: Firestore.instance.collection('items').snapshots(),
          builder: (context,snapshot) {

            if (snapshot.hasData){

             items = snapshot.data.documents.map((DocumentSnapshot document) {
                ItemModel.items(
                    itemName: document.data['name'],
                    itemPrice: document.data['price'],
                    itemImage: document.data['image']);
              }).toList();

              print("$items");


            }else{
             print("error in .....");
            }



            return GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  // crossAxisSpacing: 10,
                  // mainAxisSpacing: 10
                ),
                itemCount: items.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (BuildContext context) =>
                              ItemClick(itemModel: (items[index]))));
                    },
                    child: GridCard(items[index]),
                  );
                });
          }),
    );
  }
}

'''

4

1 回答 1

1

您可以这样做来处理未来的数据,我只是添加了一个名为 success 的标志并将其初始化为 false,因此如果该值尚未更新,则它将返回一个空文本,而当该值已更新时,它将返回您的流构建器。

      body: StreamBuilder<QuerySnapshot> (
          stream: Firestore.instance.collection('items').snapshots(),
          builder: (context,snapshot) {
            bool success = false;
            if (snapshot.hasData){

             items = snapshot.data.documents.map((DocumentSnapshot document) {
                ItemModel.items(
                    itemName: document.data['name'],
                    itemPrice: document.data['price'],
                    itemImage: document.data['image']);
              }).toList();
              success = true;
              print("$items");


            }else{
             print("error in .....");
            }

            return success == false? Text('') : GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  // crossAxisSpacing: 10,
                  // mainAxisSpacing: 10
                ),
                itemCount: items.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (BuildContext context) =>
                              ItemClick(itemModel: (items[index]))));
                    },
                    child: GridCard(items[index]),
                  );
                });
          }),
    );
  }
}
于 2020-05-08T21:29:26.080 回答