0

Here is my code. I am fetching the value TotalVotes from Firebase and showing its value in a Text-widget and I wanted to increase TotalVotes count when anyone hit button and update the Text widget. But I'm not able to update the Text-widget, and the value of the Text-widget updates only after refreshing the page.

Row(
  children: <Widget>[
    Text("Total Votes: $TotalVotes",
        style: TextStyle(color: Colors.white, fontSize: 12)),
    SizedBox(width: 30),
    FadeAnimation(
      2,
      Container(
          decoration: BoxDecoration(
              color: Color(0xFFF1f94aa).withOpacity(.6),
              borderRadius: BorderRadius.circular(8)),
          child: Padding(
            padding: const EdgeInsets.all(4.0),
            child: FadeAnimation(
                3,
                InkWell(
                  child: ItemIcon(Icons.favorite_border, "  Vote"),
                  onTap: () {
                    DatabaseReference database = FirebaseDatabase
                        .instance
                        .reference()
                        .child("Vote")
                        .child(Name);

                    database.once().then((DataSnapshot dataSnapshot) {
                      print(dataSnapshot.value['TotalVotes']);
                      String totalvote = (int.parse(
                                  dataSnapshot.value['TotalVotes']) +
                              1)
                          .toString();
                      database.child("TotalVotes").set(totalvote);
                      setState(() {
                        TotalVotes = totalvote;
                      });
                      Fluttertoast.showToast(
                          msg: 'Voted Successfully');
                    });
                  },
                )),
          )),
    ),
  ],
),

Whole Widget Code

Widget VoteForTomorrowUi(String ImageUrl,String Name,String Price,String TotalVotes,)<------------------------------------
  {

    return
      FadeAnimation(2,Container(
        margin: EdgeInsets.only(right: 20),
    height: 210,
    width: 220,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: Color(0xFFF082938)
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[

          Expanded(
            child: Container(
              width: 220,
              padding: EdgeInsets.all(10),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  image: DecorationImage(
                      image: NetworkImage(ImageUrl),
                      fit: BoxFit.fill
                  )
              ),
            ),
          ),
    Container(
      margin: EdgeInsets.all(10),
      height: 51,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text("Price: "+Price, style: TextStyle(
              color: Colors.white,
              fontSize: 12
          )),
          SizedBox(height: 5),
          Row(
            children: <Widget>[
              Text("Total Votes: $TotalVotes" ,style: TextStyle(
                  color: Colors.white,
                  fontSize: 12
              )),
              SizedBox(width: 30),
              FadeAnimation(2, Container(
                  decoration: BoxDecoration(color:Color(0xFFF1f94aa).withOpacity(.6),borderRadius: BorderRadius.circular(8)

                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: FadeAnimation(3,InkWell(
                        child: beacheItemIcon(Icons.favorite_border, "  Vote"),
                      onTap: (){
                          DatabaseReference database = FirebaseDatabase.instance.reference()
                              .child("VoteForTomorrow").child(Name);

                          database.once().then((DataSnapshot dataSnapshot){

                                  print(dataSnapshot.value['TotalVotes']);
                                  String totalvote = (int.parse(dataSnapshot.value['TotalVotes'])+1).toString();
                                  database.child("TotalVotes").set(totalvote);
                                  setState(() {
                                    TotalVotes = totalvote;  <--------------------------
                                  });
                                  Fluttertoast.showToast(msg: 'Voted Successfully');



                          });
                      },

                    )
                    ),
                  )),
              ),
            ],
          )
    ])
    )

        ],
      ),

      ) );
  }

Fade Animation


class FadeAnimation extends StatelessWidget {
  final double delay;
  final Widget child;

  FadeAnimation(this.delay, this.child);

  @override
  Widget build(BuildContext context) {
    final tween = MultiTrackTween([
      Track("opacity").add(Duration(milliseconds: 500), Tween(begin: 0.0, end: 1.0)),
      Track("translateY").add(
        Duration(milliseconds: 500), Tween(begin: -130.0, end: 0.0),
        curve: Curves.easeOut)
    ]);

    return ControlledAnimation(
      delay: Duration(milliseconds: (500 * delay).round()),
      duration: tween.duration,
      tween: tween,
      child: child,
      builderWithChild: (context, child, animation) => Opacity(
        opacity: animation["opacity"],
        child: Transform.translate(
          offset: Offset(0, animation["translateY"]), 
          child: child
        ),
      ),
    );
  }
}

Here is TotalVotes

  void initState() {
    super.initState();
    DatabaseReference postRef = FirebaseDatabase.instance.reference().child("Category");
    DatabaseReference postRef2 = FirebaseDatabase.instance.reference().child("VoteForTomorrow");
    postRef2.once().then((DataSnapshot dataSnapshot2){
      var Keys = dataSnapshot2.value.keys;
      var Datas = dataSnapshot2.value;

      voteForTomorrowList.clear();
      for(var individualKey in Keys)
        {
          VoteForTomorrow voteForTomorrow = new VoteForTomorrow(
            Datas[individualKey]['ImageUrl'],
            Datas[individualKey]['Name'],
            Datas[individualKey]['Price'],
            Datas[individualKey]['TotalVotes'],

          );
          voteForTomorrowList.add(voteForTomorrow);
        }

      setState(() {

      });
    });

And this is how I'm calling the votefortommorow

VoteForTomorrowUi(voteForTomorrowList[index].ImageUrl, voteForTomorrowList[index].Name, voteForTomorrowList[index].Price, voteForTomorrowList[index].TotalVotes);
15
  • what is Name in the second child of your firebase query is it a variable it looks like a class cause its starts with a capital letter Commented Apr 11, 2020 at 19:18
  • hey @wcyankees424 actually Name is variable which stores the name of the object in database. Commented Apr 12, 2020 at 18:24
  • I figured that it is convention to name variable in lower camel case to avoid confusion but you can name them however you like Commented Apr 12, 2020 at 21:00
  • So just to double check in firebase 'TotalVotes' is a direct child of what ever variable Name holds right so it would like this {Name: TotalVotes: xxx } where xxx is the value you are trying to access Commented Apr 12, 2020 at 23:09
  • Yes @wcyankees424, the database structure you drawn is correct. I'm able to fetch the TotalVotes and even I'm able to increase its value in database at the same time but I wanted its value to be increased in the TextWidget as well, which only happens after refreshing the page. Commented Apr 13, 2020 at 10:06

1 Answer 1

1

With out seeing your code as a whole I might be still a little confused but im using your widget and a FutureBuilder and this works

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<DataSnapshot>(
          future: FirebaseDatabase.instance
              .reference()
              .child("VoteForTomorrow")
              .child('Name')
              .child('TotalVotes')
              .once(),
          builder:
              (BuildContext context, AsyncSnapshot<DataSnapshot> snapshot) {
            return Center(
              child: VoteForTomorrowUi(
                'https://static.photocdn.pt/images/articles/2017/11/29/articles/2017_8/iStock-641093712-min.jpg',
                'Name',
                'Price',
                snapshot.data.value,
              ),
            );
          }),
    );
  }
}

I just put some dummy data in for the other values but the widget is the same the only thing I can think of is if you are reading and writing all your data properly you must be re-initializing TotalVotes every time the widget builds which is why you get the same value

Sign up to request clarification or add additional context in comments.

7 Comments

Hey @wcyankees424, Thanks for helping. I've just asked another question related to flutter and firebase can you please help me with that.
sure Im glad this helped link it and i'd be happy to take a look at it
Thank you so much.
I see you have a couple open questions can you post a link in here to the question you want help with
Hey @wcyankees424, its 4:20 am here, so I will give you reply on that question after 5-6 hours.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.