android - 从 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 和一个完全的菜鸟。
提前致谢。
解决方案
- 你确定你所有的文件都有一个“标题”字段吗?哪一行抛出错误?我想是
孩子:新文本(快照[索引].数据[“标题”][0]),
您正在访问没有标题的文档的索引 0 的位置。
这不是在 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 } )
推荐阅读
- ocaml - 将 lwt.t 代码放入 Ocaml 中用于 mirage os 的无限循环
- vue.js - vuetify上的google recaptcha 3真的没有出现吗?自动的?
- flutter - Flutter AlwaysScrollableScrollPhysics()不起作用
- javascript - Vue.js 范围问题
- powershell - 列出 Active Directory 中特定组织单位中用户的属性。有些不显示
- javascript - 功能没有定义?但它实际上是在按钮中定义的
- cookies - Chrome 80 中的 SameSite cookie 扩展更改将如何影响 Identity Server 4 用户?
- python - 如何使用 pandas 参考一个值创建虚拟变量?
- python - Hackerrank“切棒”挑战在调试中正确但不输出
- mysql - 我无法使用 Spring Batch 插入 mysql 数据库