Gbenga Ayannuga
Gbenga Ayannuga

Reputation: 41

Failed assertion: line 1916 pos 14: 'children != null': is not true.?

I have been trying to run a flutter app and it keeps giving me Failed assertion error. below is my code. I just want to show the list the second code

     class Post extends StatefulWidget {
      final String postId;
      final String ownerId;
      final String username;
      final String location;
      final String description;
      final String mediaUrl;
      final dynamic likes;
    
      Post({
        this.postId,
        this.ownerId,
        this.username,
        this.location,
        this.description,
        this.mediaUrl,
        this.likes,
      });
    
      factory Post.fromDocument(DocumentSnapshot doc) {
        return Post(
          postId: doc['postId'],
          ownerId: doc['ownerId'],
          username: doc['username'],
          location: doc['location'],
          description: doc['description'],
          mediaUrl: doc['mediaUrl'],
          likes: doc['likes'],
        );
      }
    
      int getLikeCount(likes) {
        // if no likes, return 0
        if (likes == null) {
          return 0;
        }
        int count = 0;
        // if the key is explicitly set to true, add a like
        likes.values.forEach((val) {
          if (val == true) {
            count += 1;
          }
        });
        return count;
      }
    
      @override
      _PostState createState() => _PostState(
            postId: this.postId,
            ownerId: this.ownerId,
            username: this.username,
            location: this.location,
            description: this.description,
            mediaUrl: this.mediaUrl,
            likes: this.likes,
            likeCount: getLikeCount(this.likes),
          );
    }
    
    class _PostState extends State<Post> {
      final String postId;
      final String ownerId;
      final String username;
      final String location;
      final String description;
      final String mediaUrl;
      Int likeCount;
      Map likes;
    
      _PostState({
        this.postId,
        this.ownerId,
        this.username,
        this.location,
        this.description,
        this.mediaUrl,
        this.likes,
        this.likeCount,
      });
    
      Widget postingHeading() {
        return FutureBuilder(
            future:
                FirebaseFirestore.instance.collection('User').doc(ownerId).get(),
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                return CircularProgressIndicator();
              }
              return ListTile(
                onTap: () => print('go check the url'),
                leading: CircleAvatar(
                  backgroundImage:
                      NetworkImage("${snapshot.data.data()['photoUrl']}"),
                ),
                title: Text('${snapshot.data.data()['username']}'),
                subtitle: Text(location),
                trailing: IconButton(
                  onPressed: () => print('deleting post'),
                  icon: Icon(Icons.more_vert),
                ),
              );
            });
      }
    
      Widget postImagePicture() {
        return Stack(
          alignment: Alignment.center,
          children: [
            Image.network(mediaUrl),
          ],
        );
      }
    
      Widget postDetailsComment() {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                IconButton(icon: Icon(Icons.favorite_border), onPressed: () {}),
                IconButton(icon: Icon(Icons.favorite_border), onPressed: () {})
              ],
            ),
            Row(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(left: 20.0),
                  child: Text(
                    "$likeCount likes",
                    style: TextStyle(
                      color: Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            Row(
              children: [
                Text(username),
                SizedBox(
                  width: 1,
                ),
                Flexible(child: Text(description))
              ],
            )
          ],
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            postingHeading(),
            postImagePicture(),
            postDetailsComment(),
          ],
        );
      }
    }

here is where I convert it to List... I don't even no what is wrong.... please help.... thanks in advance

    class Profile extends StatefulWidget {
  final String currentUser;
  Profile({this.currentUser});

  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  final _firestore = FirebaseFirestore.instance;
  int postLenght;
  List<Post> post;
  bool pleaseWait;
  @override
  void initState() {
    super.initState();
    getUsersPicsDetails();
  }

  getUsersPicsDetails() async {
    setState(() {
      pleaseWait = false;
    });
    QuerySnapshot _getPost = await _firestore
        .collection('post')
        .doc(widget.currentUser)
        .collection('userPost')
        .orderBy('timeStamp', descending: true)
        .get();
    setState(() {
      pleaseWait = true;
      postLenght = _getPost.docs.length;
      post = _getPost.docs.map((e) => Post.fromDocument(e)).toList();
      print(postLenght);
    });
  }

  fellowEditButtton({String test, Function press}) {
    return TextButton(
      onPressed: press,
      child: Container(
          alignment: Alignment.center,
          height: 25,
          width: 250,
          decoration: BoxDecoration(
              color: Theme.of(context).primaryColor,
              border: Border.all(),
              borderRadius: BorderRadius.circular(8.0)),
          child: Text(
            test,
            style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          )),
    );
  }

  gettingUserprofile() {
    return StreamBuilder(
      stream: _firestore.collection('User').doc(widget.currentUser).snapshots(),
      builder:
          (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
        if (!snapshot.hasData) {
          return Center(child: CircularProgressIndicator());
        }
        if (snapshot.connectionState != ConnectionState.active) {
          return Text('this stuff en');
        }
        return ListView.builder(
            itemCount: 1,
            itemBuilder: (context, index) => Container(
                  padding: EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          FullScreenWidget(
                            child: Hero(
                              tag: 'smallImage',
                              child: CircleAvatar(
                                backgroundImage: NetworkImage(
                                    '${snapshot.data.data()['photoUrl']}'),
                                radius: 50.0,
                              ),
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: [
                                    topColum(buttom: 'Post', number: 1),
                                    topColum(buttom: 'Fellowers', number: 2),
                                    topColum(buttom: 'Following', number: 0),
                                  ],
                                ),
                                Column(
                                  crossAxisAlignment:
                                      CrossAxisAlignment.stretch,
                                  children: [
                                    Padding(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 20.0,
                                        ),
                                        child: widget.currentUser ==
                                                _auth.currentUser.uid
                                            ? fellowEditButtton(
                                                test: 'Edit Profile',
                                                press: profileEditingButton)
                                            : fellowEditButtton(
                                                test: 'Fellow', press: () {})),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),

                      Divider(),
                      //! this is  i call the list
                      //getUserPicture(),
                      getUserPicture(),
                    ],
                  ),
                ));
      },
    );
  }

  profileEditingButton() {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (_) => EditProfile(
                  userProfile: widget.currentUser,
                )));
  }

  Widget topColum({int number, String buttom}) {
    return Column(
      children: [
        Text(
          '$number',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20,
          ),
        ),
        Text(
          buttom,
          style: TextStyle(
            fontSize: 20,
          ),
        ),
      ],
    );
  }

//! this is the where i return the list
  Widget getUserPicture() {
    if (pleaseWait = false) {
      return CircularProgressIndicator();
    }
    return Column(
      children: post,
    );
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: header(context, titleString: "Profile"),
        body:
            //Text('${widget.currentUser}')
            gettingUserprofile());
    // userPictursPost(),
  }
}

I want to the get the post at the bottom... thanks in advance below is the error image

enter image description here

Upvotes: 0

Views: 4909

Answers (2)

adi
adi

Reputation: 1130

For people facing similar issues, let me tell what I found in my code:

The error says that the children is null, not empty !

So if you are getting the children for the parent widget like Row or Column from a separate method, just check if you are returning the constructed child widget from the method.

Row(
  children: getMyRowChildren()
)
.
.
.

getMyRowChildren(){
    Widget childWidget = ... //constructed
    return childWidget; //don't forget to return!
}

Else it would return null, which results in the children being null and we get the mentioned above error!

Upvotes: 0

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12363

When you get an error, please post it along with your question. When you are getting an error, it means that something is wrong with your code,and most likely not the flutter engine. Both are important for debugging, the error+your code.

Try changing this

QuerySnapshot _getPost = await _firestore
    .collection('post')
    .doc(widget.currentUser)
    .collection('userPost')
    .orderBy('timeStamp', descending: true)
    .get();
setState(() {
  pleaseWait = true;
  postLenght = _getPost.docs.length;
  post = _getPost.docs.map((e) => Post.fromDocument(e)).toList();
  print(postLenght);
});

into this:

QuerySnapshot _getPost = await _firestore
    .collection('post')
    .doc(widget.currentUser)
    .collection('userPost')
    .orderBy('timeStamp', descending: true)
    .get();
if(_getPost.docs.isNotEmpty){
List<Post> tempPost = _getPost.docs.map((e) => Post.fromDocument(e)).toList();
setState(() {
  pleaseWait = true;
  post =tempPost
 
  print(postLenght);
});
}else{
print('The List is empty);}

You are not checking if the Query result has data or not. If it's empty, you will pass an empty List post down your tree, and you will get the error you are having.

Upvotes: 1

Related Questions