saif rehman
saif rehman

Reputation: 213

Setstate is not working in listview problem

As we know when setstate is called the whole widget tree is rebuild but in my i am using list of widget I have use setstate in footer but when icon button is pressed i want the tree to reubild but this doesnot happens.so i am looking for a solution. the code is given below Code

class post extends StatefulWidget {
  final DocumentSnapshot data;
  post(this.data);
  @override
  _postState createState() => _postState(data);
}
class _postState extends State<post> {
  final DocumentSnapshot data;
  _postState(this.data);    
  @override
  Widget build(BuildContext context) {
footer() {
  var like = data['likes'];
  bool islike=false ;
  islike = like.contains(Provider.of<google>(context, listen: false).Currentuser.email);
  return Container(
   
    child: Row(
      children: [IconButton(
          onPressed: () {
          if (islike == false) {
            FirebaseFirestore.instance.collection('post').doc(data['postid'])
            .update({'likes': Provider.of<google>(context, listen: false)
              .Currentuser.email
            });
            setState(() {
              islike = true;
            });
          } else if (islike = true) {
            FirebaseFirestore.instance
            .collection('post').doc(data['postid']).update({
              'likes': FieldValue.arrayRemove([Provider.of<google>(context, 
                listen:false).Currentuser.email
              ])
            });
            setState(() {
              islike = false;
            });
            }
          },
          icon: Icon(
            Icons.volunteer_activism,
            color: islike ? Colors.pink : Colors.white,
          ))
    ],
  ),
  );
}
    return Container(      
      child: Column(
        children: [
         
          footer(),
        ],),);}}

Upvotes: 1

Views: 225

Answers (2)

saif rehman
saif rehman

Reputation: 213

Full code

class Timeline extends StatefulWidget {
  static const routename = '../screen/timeline.dart';

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

class _TimelineState extends State<Timeline> {
  Future<QuerySnapshot>? posts;
  @override
  void initState() {
    setState(() {
      posts = FirebaseFirestore.instance.collection('post').get();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey,
        body: SingleChildScrollView(
          child: Column(
            children: [
              FutureBuilder(
                  future: posts,
                  builder: (context, data) {
                    QuerySnapshot? d = data.data as QuerySnapshot?;
                    if (d == null)
                      return Center(
                          child: CircularProgressIndicator(
                        color: Colors.green,
                      ));
                    List<post> list = [];
                    d.docs.forEach((element) {

                      post p = post(element);
                      list.add(p);
                    });
                    return ListView(
                      physics: NeverScrollableScrollPhysics(),
                      children: list,
                      shrinkWrap: true,
                    );
                  })
            ],
          ),
        ),
    );
  }
}

class post extends StatefulWidget {
  final DocumentSnapshot data;
  post(this.data);
  @override
  _postState createState() => _postState(data);
}

class _postState extends State<post> {
  final DocumentSnapshot data;
  _postState(this.data);
  DocumentSnapshot? u;
  Future<void> user() async {
    DocumentSnapshot d = await FirebaseFirestore.instance
        .collection('users')
        .doc(data['ownerid'])
        .get();
    setState(() {
      u = d;
    });
  }

  @override
  initState() {
    user();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    header() {
      return Container(
        decoration: BoxDecoration(
            color: Colors.black,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10), topRight: Radius.circular(10))),
        width: double.infinity,
        height: 40,
        child: Row(
          children: [
            CircleAvatar(
                maxRadius: 30,
                backgroundImage: CachedNetworkImageProvider(u!['image'])),
            Container(
                margin: EdgeInsets.only(left: 5),
                child: FittedBox(
                  fit: BoxFit.fitWidth,
                  child: Text(
                    u!['profilename'],
                    style: TextStyle(fontSize: 15, color: Colors.white),
                  ),
                )),
          ],
        ),
      );
    }

    body() {
      return Column(
        children: [
          Container(
              padding: EdgeInsets.only(left: 20),
              color: Colors.black38,
              alignment: Alignment.centerLeft,
              child: Text(
                data['caption'],
                style: TextStyle(color: Colors.white, fontSize: 20),
              )),
          Image.network(
            data["image"],
            width: double.infinity,
            height: 200,
            fit: BoxFit.fill,
          ),
        ],
      );
    }
footer() {
  var like = data['likes'];
  bool islike=false ;
  islike = like.contains(Provider.of<google>(context, listen: false).Currentuser.email);
  return Container(
    decoration: BoxDecoration(
      color: Colors.black,
      borderRadius: BorderRadius.only(
      bottomLeft: Radius.circular(10),
      bottomRight: Radius.circular(10))),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        IconButton(
          iconSize: 40,
          onPressed: () async {
          if (islike==false) {
            await FirebaseFirestore.instance
            .collection('post')
            .doc(data['postid'])
            .update({
              'likes': Provider.of<google>(context, listen: false)
              .Currentuser
              .email
            }).whenComplete(() {setState(() {
              islike = true;
            });} );

          } else if (islike==true) {
            await FirebaseFirestore.instance
            .collection('post')
            .doc(data['postid'])
            .update({
              'likes': FieldValue.arrayRemove([
              Provider.of<google>(context, listen: false)
              .Currentuser
              .email
              ])
            }).whenComplete(() {setState(() {
              islike = false;
            });} );
            }
          },
          icon: Icon(
            Icons.volunteer_activism,
            color: islike ? Colors.pink : Colors.white,
          ))
    ],
  ),
  );
}

    if (u == null)
      return Center(
        child: Text(''),
      );
    return Container(
      
      margin: EdgeInsets.only(top: 20, left: 20, right: 20),
      child: Column(
        children: [
          header(),
          body(),
          footer(),
        ],
      ),
    );
  }
}

Upvotes: 1

Abbasihsn
Abbasihsn

Reputation: 2171

you need to have two modifications:

  1. use else if (islike == true) { or else if (islike) { instead of else if (islike = true) {
  2. use the async method for a service calls! it would take some time to do the process. so use:
await FirebaseFirestore.instance
            .collection('post').doc(data['postid']).update({
              'likes': FieldValue.arrayRemove([Provider.of<google>(context, 
                listen:false).Currentuser.email
              ])
            });

Upvotes: 0

Related Questions