Reputation: 185
I am trying to render posts of a created user on profile page. The posts are stored in firestore. Having made a post widget in post.dart along with the post model. The post widget is not building.
The profile.dart has the following code for generating posts.
class Profile extends StatefulWidget {
final String profileId;
Profile({this.profileId});
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
bool isLoading = false;
int postCount = 0;
List<Post> posts = [];
final String currentUserId = currentUser?.id;
@override
void initState() {
super.initState();
getProfilePosts();
}
getProfilePosts() async {
setState(() {
isLoading=true;
});
QuerySnapshot snapshot= await userPostRef
.document(widget.profileId)
.collection('userPosts')
.getDocuments();
setState(() {
isLoading=false;
postCount=snapshot.documents.length;
posts=snapshot.documents.map((doc) =>Post.fromDocument(doc)).toList();
});
}
buildProfilePosts(){
if(isLoading){
return circularProgress();
}
return Column(children:posts);
}
@override
Widget build(context) {
return Scaffold(
appBar: header(context, titleText: "Profile"),
body: ListView(children: <Widget>[
buildProfileHeader(),
Divider(
height: 0.0,
),
buildProfilePosts(),
]),
);
}
}
Below is the post.dart file having post model and post widget
class Post extends StatefulWidget {
final String bucketId;
final String postId;
final String userId;
final String username;
final String post;
final dynamic likes;
final dynamic contributers;
final String photoUrl;
Post({
this.bucketId,
this.postId,
this.userId,
this.username,
this.post,
this.likes,
this.contributers,
this.photoUrl,
});
factory Post.fromDocument(DocumentSnapshot doc) {
return Post(
postId: doc['postId'],
userId: doc['userId'],
bucketId: doc['bucketId'],
username: doc['username'],
post: doc['post'],
contributers: doc['contributers'],
likes: doc['likes'],
photoUrl: doc['photoUrl'],
);
}
@override
_PostState createState() => _PostState(
postId: this.postId,
bucketId: this.bucketId,
userId: this.userId,
username: this.username,
post: this.post,
likes: this.likes,
contributers: this.contributers,
likeCount: getLikeCount(this.likes),
photoUrl: this.photoUrl,
);
}
class _PostState extends State<Post> {
final String currentUserId=currentUser?.id;
final String bucketId;
final String postId;
final String userId;
final String username;
final String post;
final String photoUrl;
Map likes;
Map contributers;
int likeCount;
_PostState({
this.bucketId,
this.postId,
this.userId,
this.username,
this.post,
this.likes,
this.contributers,
this.likeCount,
this.photoUrl,
});
buildPostHeader(){
return FutureBuilder(
future: usersRef.document(userId).get(),
builder: (context,snapshot){
if(!snapshot.hasData){
return circularProgress();
}
User user=User.fromDocument(snapshot.data);
bool isPostOwner = currentUserId==userId;
return ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
backgroundColor: Colors.grey,
),
title: GestureDetector(
onTap: ()=> print('showing profile'),
child: Text(
user.displayName,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold
),
),
),
subtitle: Text(
"@"+user.username,
style: TextStyle(
color: Colors.grey,
fontWeight: FontWeight.normal
),
),
trailing: isPostOwner ? IconButton(
onPressed: ()=>handleDeletePost(context),
icon: Icon(Icons.more_vert),
):Text(''),
);
}
);
}
buildPostBody(){
return GestureDetector(
onTap: ()=>print('go to bucket'),
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Card(
child: Text(
post,
),
),
],
),
);
}
buildPostFooter(){
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 40.0, left: 20.0)),
Row(
children: <Widget>[
GestureDetector (
onTap: () => print('liking post'),
child: Icon(
Icons.favorite_border,
size: 28.0,
color: Colors.pink,
),
),
Text(
likeCount.toString(),
),
],
),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => print('showing comments'),
child: Icon(
Icons.chat,
size: 28.0,
color: Colors.blue[900],
),
),
],
);
}
@override
Widget build(BuildContext context) {
print("Building widget");
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
buildPostHeader(),
buildPostBody(),
buildPostFooter(),
],
);
}
}
The debug console shows the following error
Restarted application in 1,647ms.
════════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building NotificationListener<KeepAliveNotification>:
type 'List<Object?>' is not a subtype of type 'Map<dynamic, dynamic>'
The relevant error-causing widget was
ListView
When the exception was thrown, this was the stack
#0 Post.createState
#1 new StatefulElement
#2 StatefulWidget.createElement
#3 Element.inflateWidget
#4 MultiChildRenderObjectElement.inflateWidget
...
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 258 pos 16: 'child == null || indexOf(child) > index': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
A RenderSliverPadding expected a child of type RenderSliver but received a child of type RenderErrorBox.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
ListView
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Scaffold
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Profile
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
'package:flutter/src/widgets/framework.dart': Failed assertion: line 4269 pos 14: 'owner!._debugCurrentBuildTarget == this': is not true.
The relevant error-causing widget was
Profile
════════════════════════════════════════════════════════════════════════════════
Upvotes: 5
Views: 372
Reputation: 3477
There is way too much going on. Please strip your example. I am unable to copy and execute the code because dependencies are missing (like the User
class).
The code is very messy, you're mixing view logic, application logic, models, and view models everywhere which makes it hard to grasp, where and why the exception arises. Also, you work with Map
s because the Firestore returns these kinds of data types. Instead you should convert the dynamic Map
s to your own (view)model classes. This way, the compiler could give a much better explanation about what's wrong.
It has probably something to do with the properties you have declared as dynamic
("likes" and "contributers"). Have you tried to debug whether they are really Map
s and not List
s? Because in the Post
constructor you declare them as dynamic
whereas in the PostState
you expect Map
s.
Can you at least narrow the issue down to a Widget? Does the problem persist when you don't render the header and footer?
Upvotes: 2
Reputation: 1782
Try these changes,
change your code from,
posts=snapshot.documents.map((doc) =>Post.fromDocument(doc)).toList()
to,
posts=snapshot.documents.map((doc) =>Post.fromDocument(doc))
As firestore already returns list of objects for your request and you are again converting that to list so it might be the possible error cause. So removing your .toList()
method should solve the error.
first run with the above changes if that didnt worked out then go ahead with below changes too,
then try removing your posts
and postCount
in setState
it should be outside of setState method and run your project it might solve the error
and also you should use async
and await
in your code for getting the data from firestore otherwise your data which is fetched will be incomplete
for more info on QuerySnapshot refer this:
what does QuerySnapshot returns Returns the list of documents that changed since the last snapshot. If it's the first snapshot all documents will be in the list as added changes
Upvotes: 0
Reputation: 4884
profile.dart
getProfilePosts() async {
setState(() {
isLoading=true;
});
QuerySnapshot snapshot= await userPostRef
.document(widget.profileId)
.collection('userPosts')
.getDocuments();
setState(() {
isLoading=false;
postCount=snapshot.documents.length;
posts=snapshot.documents.map((doc){
Post.fromDocument(doc)
}).toList();
});
}
In post.dart
change factory method to this
factory Post.fromDocument(DocumentSnapshot document) {
Map<String, dynamic> doc = document.data()! as Map<String, dynamic>;
return Post(
postId: doc['postId'],
userId: doc['userId'],
bucketId: doc['bucketId'],
username: doc['username'],
post: doc['post'],
contributers: doc['contributers'],
likes: doc['likes'],
photoUrl: doc['photoUrl'],
);
}
Try this
Upvotes: 1