Получение следующей ошибки при импорте данных из Firebase: метод '[]' был вызван с нулевым значением - PullRequest
0 голосов
/ 04 марта 2020

Я пытаюсь создать простое приложение, которое читает данные из 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 есть одна запись, приложение работает нормально, но когда я ввожу другой набор данные, это показывает мне эту ошибку. Кто-нибудь может помочь мне с этим. Я только начинаю изучать Флаттер и полный нуб.

Заранее спасибо.

1 Ответ

0 голосов
/ 05 марта 2020
  1. Вы уверены, что все ваши документы имеют поле 'title'? Какая строка выдает ошибку? Я предполагаю, что это

child: новый текст (снимок [index] .data ["title"] [0]),

, к которому вы обращаетесь индекс 0 документа, который не имеет заголовка.

Это не предпочтительный способ доступа к потокам Firestore во Flutter, так как вам нужно самостоятельно позаботиться о жизненном цикле подписки. Попробуйте использовать 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
      } 
   )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...