单击按钮动态更改文本小部件文本

时间:2020-04-11 18:15:40

标签: flutter

这是我的代码。我正在从Firebase中获取值TotalVotes,并在Text小部件中显示其值,我想在有人按下按钮并更新TotalVotes小部件时增加Text的数量。但是我无法更新Text小部件,而Text小部件的值仅在刷新页面后才更新。

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');
                    });
                  },
                )),
          )),
    ),
  ],
),

整个小部件代码

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');



                          });
                      },

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

        ],
      ),

      ) );
  }

淡入淡出动画


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
        ),
      ),
    );
  }
}

这是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(() {

      });
    });

这就是我所谓的明天投票

VoteForTomorrowUi(voteForTomorrowList[index].ImageUrl, voteForTomorrowList[index].Name, voteForTomorrowList[index].Price, voteForTomorrowList[index].TotalVotes);

1 个答案:

答案 0 :(得分:1)

虽然看不到您的代码整体,但我可能还是有些困惑,但是我正在使用您的小部件和list_all_leagues = ['L1', 'GB1', 'IT1', 'FR1', 'ES1'] # codes for the top 5 European leagues ,并且可以正常工作

FutureBuilder

我只是在其他值中放入了一些虚拟数据,但小部件是相同的,我唯一能想到的是,如果您正确地读写所有数据,则必须每次重新初始化 @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, ), ); }), ); } } 小部件构建的时间,这就是为什么您获得相同值的原因