【问题标题】:Getting the following error while importing data from Firebase:The method '[]' was called on null从 Firebase 导入数据时出现以下错误:在 null 上调用了方法“[]”
【发布时间】:2020-03-05 16:21:43
【问题描述】:

我正在尝试创建一个简单的应用程序,该应用程序从 Firestore Firebase 读取数据并将其显示在应用程序上给用户。它基本上是一个简单的博客应用程序。

这是我的代码:

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:async/async.dart';
import 'dart:async';


class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  StreamSubscription<QuerySnapshot>subscription;

  List<DocumentSnapshot>snapshot;

  CollectionReference collectionReference=Firestore.instance.collection("Post");

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    subscription=collectionReference.snapshots().listen((datasnapshot){
      setState(() {
        snapshot=datasnapshot.documents;
      });
    });

  }


  @override
  Widget build(BuildContext context) {
    return new Scaffold(

      appBar: new AppBar(
        title: new Text("Blog App Demo"),
        backgroundColor: Colors.redAccent,

        actions: <Widget>[

          new IconButton(
              icon: new Icon(Icons.search),
              onPressed: ()=>debugPrint("Searching...")
          ),

          new IconButton(
              icon: Icon(Icons.ac_unit),
              onPressed: ()=>debugPrint("Chilling...")
          )

        ],
      ),

      drawer: new Drawer(
        child: new ListView(
          children: <Widget>[
            new UserAccountsDrawerHeader(
                accountName: new Text("Priyanuj Dey"),
                accountEmail: new Text("priyanujdey@gmail.com"),
              decoration: new BoxDecoration(
                color: Colors.lightBlueAccent,
              ),

            ),

            new ListTile(
              title: new Text("Profile"),
              leading: new Icon(Icons.account_box, color: Colors.deepPurpleAccent),          //trailing for right
            ),

            new ListTile(
              title: new Text("Settings"),
              leading: new Icon(Icons.build, color: Colors.deepPurpleAccent),          //trailing for right
            ),

            new Divider(
              height: 10.0,
              color: Colors.black45,
            ),

            new ListTile(
              title: new Text("Close"),
              trailing: new Icon(Icons.close, color: Colors.red),          //leading for left
              onTap: () {
                Navigator.of(context).pop();
              },
            ),



          ],
        )
      ),

      body: new ListView.builder(
          itemCount: snapshot.length,
          itemBuilder: (context,index){
            return new Card(
              elevation: 10.0,
              margin: EdgeInsets.all(10.0),

              child: new Container(

                padding: EdgeInsets.all(10.0),

              child: new Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  new CircleAvatar(
                    child: new Text(snapshot[index].data["title"][0]),
                    backgroundColor: Colors.orangeAccent,
                    foregroundColor: Colors.white,
                  ),

                  new SizedBox(width: 15.0,),

                  new Container(
                    width: 210.0,
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[

                        new Text(snapshot[index].data["title"],
                        style: TextStyle(fontSize: 22.0, color: Colors.lightGreen),
                          maxLines: 1,
                        ),

                        new SizedBox(height: 5.0,),

                        new Text(snapshot[index].data["content"],
                        maxLines: 2,

                        ),

                      ]
                    ),
                  )

                ],
              ),
            )
            );
          }
      )



    );
  }
}

当 Firebase 中有一个条目时,该应用程序运行良好,但当我输入另一组数据时,它会显示此错误。 任何人都可以帮我解决这个问题。 我刚刚开始学习 Flutter 和它的新手。

提前致谢。

【问题讨论】:

    标签: android firebase flutter dart


    【解决方案1】:
    1. 您确定所有文档都有“标题”字段吗?哪一行抛出错误?我想是

    子:新文本(snapshot[index].data["title"][0]),

    您正在访问没有标题的文档的索引 0。

    1. 这不是在 Flutter 中访问 Firestore 流的首选方式,因为必须自己处理订阅的生命周期。考虑使用StreamBuilder。以下是如何使用它的示例:

         body: StreamBuilder<QuerySnapshot>(
            stream: Firestore.instance.collection("Post").snapshots(),
            builder: (context, snapshot) {
               if (!snapshot.hasData) //You are still loading data
                 return Center(child: CircularProgressIndicator());
               return ListView.builder(...) //Here you do as you are used to
            } 
         )
      

    【讨论】:

    • 是的。我有一个“标题”字段。此外,当我在 firestore 数据库中添加两行或多行时,问题就出现了。如果只有一个,没有问题。在此处上传应用的屏幕截图。
    • 错误:错误:“用户数据”不是一种类型。错误:没有为类 'AsyncSnapshot' 定义 getter 'length'。错误:没有为类“AsyncSnapshot”定义方法“[]”。没有为类“AsyncSnapshot”定义方法“[]”。不能将参数类型“Stream”分配给参数类型“Stream”。 - 'Stream' 来自 'dart:async'。
    • 抱歉,“用户数据”是我从其中复制的剩余部分。请改用 QuerySnapshot。我编辑了我的评论
    • 感谢@Thomas 的回复。但问题在于我向数据库添加数据的方式。我不知何故忽略了一些愚蠢的错误,这造成了问题。
    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 2020-07-14
    • 2020-07-31
    • 2020-08-31
    • 2021-07-24
    • 1970-01-01
    • 2021-11-08
    • 2021-06-01
    相关资源
    最近更新 更多