这是FutureBuilder:
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: postsRef
.document(userId)
.collection('userPosts')
.document(postId)
.get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
Post post = Post.fromDocument(snapshot.data);
return Center(
child: Scaffold(
appBar: header(context, titleText: post.description),
body: ListView(
children: <Widget>[
Container(
child: post,
)
],
),
),
);
},
);
}
引用它的show post方法:
showPost(context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PostScreen(
postId: postId,
userId: userId,
),
),
);
}
遇到错误
方法'[]'在null上被调用。 接收者:null 尝试致电: 相关的引起错误的小部件是: FutureBuilder文件:///home/testflutter/AndroidStudioProjects/testingflutter/lib/pages/post_screen.dart:15:12
答案 0 :(得分:0)
添加else
子句
Widget build(BuildContext context) {
return FutureBuilder(
future: postsRef
.document(userId)
.collection('userPosts')
.document(postId)
.get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
else {
Post post = Post.fromDocument(snapshot.data);
return Center(
child: Scaffold(
appBar: header(context, titleText: post.description),
body: ListView(
children: <Widget>[
Container(
child: post,
)
],
),
),
);
}
},
);
答案 1 :(得分:0)
检查快照的ConnectionState
,看是否已完成。
Widget build(BuildContext context) {
return FutureBuilder(
future: postsRef
.document(userId)
.collection('userPosts')
.document(postId)
.get(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return circularProgress();
else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData && snapshot.data.isNotEmpty) {
Post post = Post.fromDocument(snapshot.data);
return Center(
child: Scaffold(
appBar: header(context, titleText: post.description),
body: ListView(
children: <Widget>[
Container(
child: post,
),
],
),
),
);
} else {
return Center(child: Text("No data or it's empty"));
}
} else {
return Center(child: Text("Neither waiting or done..."));
}
},
);
}
我已修正代码以使其变得容易,并添加了else子句。
答案 2 :(得分:-1)
可能的错误是在您的 showPost() 方法中。
在您的 home.dart 文件中初始化一个 User 对象。
User currentUser;
然后像这样更新 showPost() 方法:
showPost(BuildContext context) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
PostScreen(userId: currentUser.id, postId: postId),
),
);
}