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
════════════════════════════════════════════════════════════════════════════════
To create a stateful widget in a flutter, use the createState() method. The stateful widget is the widget that describes part of a user interface by building a constellation of other widgets that represent a user interface more concretely. A stateful Widget means a widget that has a mutable state.
One of the easiest ways to avoid unwanted reBuilds that are caused usually by calling setState() in order to update only a specific Widget and not refreshing the whole page, is to cut that part of your code and wrap it as an independent Widget in another Stateful class.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With