首页 > 解决方案 > 从 Firebase 导入数据时出现以下错误:在 null 上调用了方法“[]”

问题描述

我正在尝试创建一个简单的应用程序,它从 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 和一个完全的菜鸟。

提前致谢。

标签: androidfirebaseflutterdart

解决方案


  1. 你确定你所有的文件都有一个“标题”字段吗?哪一行抛出错误?我想是

孩子:新文本(快照[索引].数据[“标题”][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
          } 
       )
    

推荐阅读